0

I am trying to navigate to a folder in my linux box and update a file using paramiko.

Here do I need to enter all the commands at once by separating with ';' or is there any way to maintain a session.

Could you please suggest with the same.

import paramiko

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('1.1.1.1',username='abc',password='bnw')


cmd = 'cd rtg-demo/app-demo;pwd'
stdin, stdout, stderr = ssh.exec_command(cmd)
print(stdout.readlines())
stdin, stdout, stderr = ssh.exec_command('pwd')
print(stdout.readlines())

Here for the first print statement I am getting the correct path to which I have navigated. But for second print statement, I am seeing the home directory path.

Output is as below

['/remote/users/abc/rtg-demo/app-demo\n']
['/remote/users/abc\n']
K S S Srihari
  • 29
  • 1
  • 5
  • But if I have many statements to execute. For Eg: I need to navigate to a path and verify if a file is present and then open and update the file. I cannot provide all the commands at once. How can I do that with paramiko. – K S S Srihari Feb 19 '20 at 07:44
  • Suppose I need to navigate to a path, I will provide cd command. Then I have to dir to get the list of files. After that only if a particular file is present then I have to run the command ssh.exec_command('vi filename) – K S S Srihari Feb 19 '20 at 07:54
  • 1) Avoid "navigating" to a path, use absolute paths instead. 2) "dir" and running commands over the returned list are not dependent commands. You can execute them using separate `exec_command` calls. 3) To retrieve a list of files, you should use SFTP and not shell commands anyway. – If you want to do it your hackish way anyway, this is already answered in [Execute multiple dependent commands individually with Paramiko and find out when each command finishes](https://stackoverflow.com/q/50962485/850848) (indirectly linked from the question I've linked above) – Martin Prikryl Feb 19 '20 at 08:02
  • In general, do not try to implement the steps you would do in an interactive shell. Find out simpler ways to automate your operation. E.g. do not do `cd /path; ls`, do `ls /path`, etc. – Martin Prikryl Feb 19 '20 at 08:07

0 Answers0