Python paramiko run command

I am trying to run this script:

hostname = '192.168.3.4' port = 22 username = 'username' password = 'mypassword' y = "2012" m = "02" d = "27" if __name__ == "__main__": s = paramiko.SSHClient() s.load_system_host_keys() s.connect(hostname, port, username, password) command = 'ls /home/user/images/cappi/03000/y/m/d' s.close 

Question: how can I put the variables y , m , d in the command variable?

+4
source share
3 answers

Python has many ways to perform string formatting. One of the easiest is to simply combine parts of your string together:

 #!/usr/bin/env python hostname = '192.168.3.4' port = 22 username = 'username' password = 'mypassword' y = "2012" m = "02" d = "27" def do_it(): s = paramiko.SSHClient() s.load_system_host_keys() s.connect(hostname, port, username, password) command = 'ls /home/user/images/cappi/03000/' + y + '/' + m + '/' + d (stdin, stdout, stderr) = s.exec_command(command) for line in stdout.readlines(): print line s.close() if __name__ == "main": do_it() 
+9
source
 command = 'ls /home/user/images/cappi/03000/%s/%s/%s' %(y,m,d) 
+3
source

Using the specifications of the new format , you can access arguments by name:

 'ls /home/user/images/cappi/03000/{year}/{month}/{day}'.format(year=y, month=m, day=d) 
+2
source

All Articles