0

I need to edit the remote file. Right now, I'm logging into the machine via SSH. I can execute commands and get back response etc.

I am facing difficulty to modify the remote file.

Source Machine : Windows
Destination : Linux

Is anything like, get the file to Windows machine and edit it and then again transfer the file to Linux ? or any other better way ?

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

Can you please help me ?

jww
  • 97,681
  • 90
  • 411
  • 885
Diesel Kumar
  • 215
  • 4
  • 11
  • 22

2 Answers2

0

try python paramiko and linux cat and 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()
Ron
  • 197
  • 1
  • 10
0

Use SFTP (SSH file transfer protocol). That's a protocol designed for file transfers.

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()

(base on paramiko's sshclient with sftp)

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992