我需要使用Python访问并打开服务器上的文件。 我有一台Centos服务器,可以通过ssh root@172.24.2.233
从终端访问,然后输入用户密码。
问题
如果服务器上的文件位于此路径中:/var/document.txt
要访问此路径并打开本地计算机上的document.txt
,我应该写什么?
如果该文件在我的本地计算机上,我可以使用以下命令读取它:
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')
如果文件在服务器上,我如何访问它?
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)
我不确定我是否理解您想要实现的目标,您是想要将文件(scp)传输到本地计算机,还是想要在本地计算机上打开/查看该文件,但是一个快速且简单的方法是在您想要查看/下载该文件的计算机上启动http服务器。
ssh root@172.24.2.233
之后:
cd /var/document.txt
# if you have python2
python -m SimpleHTTPServer 5050
# if you have python3
python3 -m http.server 5050
然后您将拥有一个http服务器(在0.0.0.0端口5050上提供http服务…
),您可以从端口5050上的浏览器访问它,查看甚至下载所需的文件。