Issue
This is running Python 2.7.5, on a CentOS Linux release 7.6.1810 (Core) system. I do not have a lot of experience with Python. But I have looked at a number of previous questions/examples and cannot figure out how to proceed with this issue. I'm unsuccessful running a Linux ssh command from a Python script. However, when I run a Linux echo command I get expected results. I'll provide the code and both outputs:
#!/bin/python
import sys
import subprocess
tunnelUser='testuser'
localIP = []
localPort = []
remoteIP = []
remotePort = []
x = 0
vfile=open('/home/'+tunnelUser+'/development/scripts/port-dummy-data','rt')
for line in vfile:
columns = line.split(',')
localIP.append(columns[0])
localPort.append(columns[1])
remoteIP.append(columns[2])
remotePort.append(columns[3])
sshCommand = " -f -N "+tunnelUser+"@"+localIP[x]+" -R "+localPort[x]\
+":"+remoteIP[x]+":"+remotePort[x]
subprocess.Popen(['/bin/ssh', sshCommand])
# subprocess.Popen(['/bin/echo', sshCommand])
x=x+1
sys.stdout.close()
Yields the following negative results:
prompt > ./create-tunnels.py
prompt > ssh: Could not resolve hostname localhost -r 8080:192.168.1.3:8080
: Name or service not known
ssh: Could not resolve hostname localhost -r 8090:192.168.1.11:8090
: Name or service not known
ssh: Could not resolve hostname localhost -r 8081:192.168.1.5:8081
: Name or service not known
ssh: Could not resolve hostname localhost -r 8085:192.168.1.9:8085
: Name or service not known
ssh: Could not resolve hostname localhost -r 8095:192.168.1.12:8095
: Name or service not known
Yet when I "comment out" the ssh and "uncomment" the echo, I get the expected results:
prompt > ./create-tunnels.py
-f -N testuser@localhost -R 8080:192.168.1.3:8080
-f -N testuser@localhost -R 8081:192.168.1.5:8081
-f -N testuser@localhost -R 8085:192.168.1.9:8085
-f -N testuser@localhost -R 8090:192.168.1.11:8090
-f -N testuser@localhost -R 8095:192.168.1.12:8095
I believe I'm missing something simple due to lack of Python experience. Any help would be appreciated.
Solution
The individual arguments to Popen()
should be passed as a list, i.e. something like
Popen(['/bin/ssh', '-f', '-N', tunnelUser+"@"+localIP[x], '-R', ...])
But instead you're passing the arguments as one giant string. So it's trying to interpret the entire literal string localhost -r 8080:192.168.1.3:8080
as one hostname.
Also, why does the unsuccessful output block contain the -r
flag, when the code has it as -R
?
Answered By - John Gordon