Hello I am new to python. trying to use a list to ssh to my remote server
#!/usr/bin/python
import subprocess
node = ['node41', 'node42', 'node52']
link = ['eth0', 'eth0', 'eht0']
for i in range(len(node)):
print node[i], s16d1[i]
subprocess.call(["ssh", node[i], 'ip link show s16d1[i]'])
getting his error
Error:
Device "link[i]" does not exist.
How can I pass device link from the list ssh remote command?
thanks,
Quote:How can I pass device link from the list ssh remote command?
In shell you do it via:
ssh host "command"
Command is one argument.
In Python you've to use a list. Each element is a argument, the first argument is the binary itself.
command = ['ssh', 'node', 'ip link show eth0']
stdout = subprocess.check_output(command)
I think you're using Public-Key authentication. If you want to use password authentication, you have to do it different. There is a module for it:
http://www.paramiko.org/
Finally this should work with Python 2.7 and Python 3.x:
#!/usr/bin/python
from __future__ import print_function
# to be compatible with Python 3.x, print is since Python 3 a function and no longer a statement
from subprocess import check_output
# using check_output instead of using Popen
# call returns the exit code
def get_links(nodes, links):
for node, link in zip(nodes, links):
# zip can zip lists together
# and assigned to node, link
# now format the command for the target host
ip_command = 'ip link show {}'.format(link)
# finally make a list for the ssh command
command = ['ssh', node, ip_command]
# save output to stdout
stdout = check_output(command)
# just print it. You can process also the output
print(stdout.decode())
# or
# return stdout
def main():
# use plural for lists and not singular
nodes = ['node41', 'node42', 'node52']
links = ['eth0', 'eth0', 'eht0']
get_links(nodes, links)
if __name__ == '__main__':
main()
Thanks DeaD_EyE!
You hint of "ip_command = 'ip link show {}'.format(link)" helped
#!/usr/bin/python
import subprocess
node = ['node41', 'node42', 'node52']
link = ['eth0', 'eth0', 'eht0']
for i in range(len(node)):
ip_command = 'ip link show {}'.format(link[i])
print ip_command
subprocess.call(["ssh", node[i], ip_command])