Unnikrishnan V Unnikrishnan V - 5 months ago 15
Python Question

python solution to ssh into a linux server and edit a file

it worked. But now I am having a new problem. I am able to login to server using paramiko. But cant execute any commands. My code is as follows. I am suspecting issues with connection.send command.

session = paramiko.SSHClient()
session.set_missing_host_key_policy(paramiko.AutoAddPolicy())
session.connect('192.168.0.20',port=22,username='admin',password='netvanta')
connection = session.invoke_shell()
connection.send('su')
connection.send('password')


It is not taking my commands to super user login. with out super user login I cant write to the file. Please help.

Answer

Take a look at this demo for the paramiko package.

After connecting to the server, like in the demo, this is how I would edit the remote file:

with sftp.open("yourfiletoedit", "rb") as f:
    data = f.read()

# modify the data of the file (this depends on the format wich was not specified)

with sftp.open("yourfiletoedit", "wb") as f:
    f.write(data)
Comments