简体   繁体   English

如何使用 python 从服务器打开文件?

[英]How to open file from server with python?

I need to access and open a file on a server with python.我需要使用 python 访问并打开服务器上的文件。 I have a Centos server which I can access from terminal with ssh root@172.24.2.233 and enter the user password.我有一个 Centos 服务器,我可以使用ssh root@172.24.2.233终端访问它并输入用户密码。

Question问题
If I have a file on the server in this path: /var/document.txt what do I write to access that path and open the document.txt on my local machine?如果我在此路径中的服务器上有一个文件: /var/document.txt我要写什么来访问该路径并在我的本地计算机上打开document.txt

If the file was on my local machine, I could read it with this:如果文件在我的本地机器上,我可以这样读取它:

import glob

# for example if i want to see file in the folder
for f in glob.glob('/var/*.*'):
    print(f) # output --> document.txt
    # read file
    read = open(f, 'r')

How do I access the file if it is on the server?如果文件在服务器上,我如何访问它? I do not want to download the file, edit it and upload it again.我不想下载文件,编辑它并再次上传。

from contextlib     import closing
from fabric.network import connect
user = 'root' # your SSH user
password = 'secret' # your SSH password
host = '172.24.2.233' #IP of your server
port = '22' #SSH Port
remote_file = '/var/document.txt'
with closing(connect(user, password, host, port)) as ssh, \
     closing(ssh.open_sftp()) as sftp, \
     closing(sftp.open(remote_file)) as file:
    for line in file:
        print(line)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM