I’m try 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
The question is:
how can I put the variables y,m,d into the variable command ?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Python has lots of ways to perform string formatting. One of the simplest is to simply concatenate the 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()
Method 2
command = 'ls /home/user/images/cappi/03000/%s/%s/%s' %(y,m,d)
Method 3
Using the new format specifications, you can access arguments by name:
'ls /home/user/images/cappi/03000/{year}/{month}/{day}'.format(year=y, month=m, day=d)
Method 4
I prefer
command = f"ls /home/user/images/cappi/03000/{y}/{m}/{d}"
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0