I'm trying to do ssh through middle server with python.
I tried to work as written at this example : SSH to machine through a middle host
but when I'm running the code, I'm getting the following exception paramiko.ssh_exception.SSHException: Error reading SSH protocol banner
When I'm opens the terminal that executes the program password authentication is required in order to proceed
I also edited the ~/.ssh/config as follows:
Host cybnode13
ProxyCommand ssh root#cybhead1.lnx.biu.ac.il nc %h %p
My code is attached below
proxy_command = 'ssh -p %s %s#%s nc %s %s' % (password, proxy_user, proxy_host, host, 22)
proxy = paramiko.ProxyCommand(proxy_command)
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(host, username=proxy_user, password=password, sock=proxy)
stdin, stdout, stderr = client.exec_command('echo HELLO')
Related
I have written a simple script that I want to run remotely to a Windows server using Python and Paramiko. The script should execute commands in the cmd on the remote Windows server and I want it to start up an .exe program for a starter. Here is what I have up to now:
import paramiko
hostname = "IP_of_server"
username = "username"
password = "password"
command = "start Full_Path_To_Application\Program.exe"
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname, username=username, password=password, look_for_keys=True, allow_agent=False)
print("Connected to %s" % hostname)
except paramiko.AuthenticationException:
print("Failed to connect to %s due to wrong username/password" %hostname)
exit(1)
try:
stdin, stdout, stderr = ssh.exec_command(command)
for line in stdout.readlines():
print(line)
print("Application has been started")
except:
exit(2)
What I get is:
Connected to IP_of_server
Application has been started
When I check on the server using the same username and password the application is not running. Running it manually starts it up.
I have confirmed that the command has been sent to the server by replacing it with "ipconfig" and I get the correct information.
Any idea why the application is not starting? Once it starts it should open a separate cmd with all the logs that I'm not seeing.
Thanks a lot.
I have executed commands on server using ssh. Now I have to do another ssh to different IP while keeping old ssh active.
This new IP is port forward which will then used to do SFTP.
Issue I am facing is both ssh connections are on same port so not able to do second ssh.
Which is failing the SFTP.
Any support for same will be helpful.
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip, username=username, password=password, port=22)
time.sleep(3)
#Invoke shell to open multiple channel with in one SSH
chan = ssh.invoke_shell()
chan.send(ip1+'\n')
time.sleep(5)
chan.send(pass1+'\n')
time.sleep(10)
chan.send("ssh "+ip2+'\n')
time.sleep(10)
chan.send(pass2+'\n')
time.sleep(5)
#Execute command
chan.send(cmd)
#connect to another ip to do sftp
ssh1 = paramiko.SSHClient()
ssh1.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect("127.0.0.4", username=usr2, password=pass2, port=22)
sftp=ssh.open_sftp()
It looks like misunderstanding. Your code does not do any port forwarding.
For the correct code, see Nested SSH using Python Paramiko.
If you need SFTP, not shell, just do:
jhost.open_sftp()
instead of
jhost.exec_command(command)
Obligatory warning: Do not use AutoAddPolicy – You are losing a protection against MITM attacks by doing so. For a correct solution, see Paramiko "Unknown Server".
This question already has answers here:
Connecting to a server via another server using Paramiko
(1 answer)
Paramiko: read from standard output of remotely executed command
(5 answers)
Closed 3 years ago.
My goal is to connect to a server using ssh and then ssh again into a router in that server using paramiko.
This is what I have tried.
username, password, port = credentials...
hostname = 1st server
router = router server
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.WarningPolicy)
client.connect(hostname, port = port, username = username, password = password)
print("connecting to {} from {} as {}".format(router, hostname, username))
# Calls syslog.py from the server
cmd = "ssh {}#{}".format('root', router)
print('command = {}'.format(cmd))
stdin, stdout, stderr = client.exec_command(cmd, get_pty = True)
stdin.write(pw here)
stdin.flush()
stdin.write('show ?\n')
stdin.flush()
client.close()
I am connecting into the server and then the router and run show ? in the router.
show ? is supposed to give me a list of all possible commands starting with show. However, when I run the script, it gives me
connecting to <router ip> from <1st server> as root
command = ssh root#<router ip>
and then it just ends without showing the result of show ?
It's really hard to catch the issue because it doesn't show an error.
Any help please?
I need to connect to SFTP server using proxy command.
I know how to connect to SFTP server directly:
paramiko's sshclient with sftp
I can open an SSH connection via proxy command using this code:
import paramiko
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
target_host = 'sftp.XXXXX.co'
target_port = 22
proxy = paramiko.proxy.ProxyCommand('/usr/bin/nc --proxy proxy_host:8080 %s %d' % (target_host, target_port) )
client.connect(hostname=target_host,username='username', port=target_port, password='XXXXXXXX', sock=proxy)
But I need to create SFTPClient, not SSHClient. But I do not know how to pass the ProxyCommand to the SFTPClient.
To connect to SFTP server using a "custom socket", do:
proxy = paramiko.proxy.ProxyCommand(...)
transport = paramiko.Transport(proxy)
transport.connect(username = username, password = password)
sftp = paramiko.SFTPClient.from_transport(transport)
I am trying to connect via SSH to a computer tunneling through another computer using paramiko in Python, but I am having some strange issues.
My config file in /.ssh/config looks like this:
Host remoteA
HostName 169.254.1.1
User root
IdentityFile ~/.ssh/id_dss.openssh.remoteA
ForwardX11 no
StrictHostKeyChecking no
ForwardAgent yes
UserKnownHostsFile /dev/null
Host remoteB
User root
IdentityFile ~/.ssh/id_dss.openssh.remoteB
ForwardX11 no
StrictHostKeyChecking no
UserKnownHostsFile /dev/null
ProxyCommand ssh -W 169.254.1.2:22 remoteA
And my python code like this:
from paramiko import SSHClient,SSHConfig,SSHException
import getpass
import paramiko
def getSSHConnection(hostName):
config = SSHConfig()
user = getpass.getuser()
config.parse(open('C:/Users/' + user +'/.ssh/config'))
host=config.lookup(hostName)
# setup SSH client
client = SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#Check for proxy settings
try:
print host ['proxycommand']
proxy = paramiko.ProxyCommand(host['proxycommand'])
except:
proxy = None
#Setup the SSH connection
try:
if (proxy is None):
client.connect(host['hostname'],22,username=host['user'],key_filename=host['identityfile'])
else:
client.connect(host['hostname'],22,username=host['user'], key_filename=host['identityfile'],sock=proxy)
except SSHException,ex:
print ex
return client
ssh_client = getSSHConnection('remoteA')
# run a command
print "\nRun a command"
cmd = 'ps aux'
stdin,stdout,stderr = ssh_client.exec_command(cmd)
print stdout.read()
ssh_client = getSSHConnection('remoteB')
# run a command
print "\nRun a command"
cmd = 'ps aux'
stdin,stdout,stderr = ssh_client.exec_command(cmd)
print stdout.read()
First when connecting to remoteA it works perfectly,but then when connecting to remoteB it crashes in the step: proxy = paramiko.ProxyCommand(host['proxycommand']).
File "C:\Python27\lib\site-packages\paramiko\client.py",line 291,in connect
for (family,socktype,proto,canonname,sockaddr) in socket.getaddrinfo(hostname,port, socket.AF_UNSPEC,socket.SOCK_STREAM):
socket.gaierror: [Errno 11004] getaddrinfo failed
Within Cygwin,I am able to connect using the command ssh remoteB so I know the config file should be ok.
If it makes any difference,I am running this on Windows 7.
I think you can stick to your first solution. Just you need to change your proxy command and make sure your jump host has got nc installed
I use a proxy command like this
proxy = paramiko.ProxyCommand("ssh -o StrictHostKeyChecking=no jumphostIP nc targethostIP 22")
I found this WiKi very useful
http://en.wikibooks.org/wiki/OpenSSH/Cookbook/Proxies_and_Jump_Hosts
Just use actual values instead of %h and %p as I have done.
So instead of using ProxyCommand I used port forwarding to solve my issue.
def getForwardedSSHPort(self, tunnnelHostName):
forwarderClient = self.getSSHConnection(tunnnelHostName, None)
transport = forwarderClient.get_transport()
dest_addr = ('169.254.1.2', 22)
local_addr = ('127.0.0.1', 10022)
channel = transport.open_channel('direct-tcpip', dest_addr, local_addr)
remoteClient = self.getSSHConnection( tunnnelHostName, channel)