如何通过SSHLibrary编辑远程文件?

时间:2017-11-12 18:25:47

标签: linux windows python-2.7 ssh

我需要编辑远程文件。 现在,我正在通过SSH登录机器。我可以执行命令并获得响应等。

我很难修改远程文件。

Source Machine : Windows
Destination : Linux

是不是这样,将文件送到Windows机器并编辑它然后再将文件传输到Linux?或任何其他更好的方式?

import SSHLibrary
s = SSHLibrary.SSHLibrary()
s.open_connection("10.10.10.10",username, password)
#s.write("sudo vi file_name_along_with_path") it has to force edit the file
# any ftp mechanism would be better

你能帮帮我吗?

2 个答案:

答案 0 :(得分:0)

尝试使用python paramiko和linux cat并使用echo not vi。

import paramiko

host = 'test.example.com'
username='host_user_name'
password='host_password'
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=host, username=username, password=password)
stdin, stdout, stderr = ssh.exec_command("cat path_to_file_for_read")
all_lines = ''
for line in stdout.readlines():
    all_lines += line
new_line = all_lines + 'add more or edit'
print new_line
stdin, stdout, stderr = ssh.exec_command("echo '{}' >> path_of_file_to_write".format(new_line))
ssh.close()

答案 1 :(得分:0)

使用SFTP(SSH文件传输协议)。这是一个专为文件传输而设计的协议。

import paramiko

host = "sftp.example.com"
transport = paramiko.Transport(host)
transport.connect(username = "username", password = "password")

sftp = paramiko.SFTPClient.from_transport(transport)

# Download

filepath = '/remote/path/file.txt'
localpath = '/tmp/file.txt'
sftp.get(filepath, localpath)

# Open in your favorite editor here

# Upload back

sftp.put(localpath, filepath)

# Close

sftp.close()
transport.close()

(基于paramiko's sshclient with sftp