Create a SSH session connect to device through a terminal server - python

I want to connect to a network device. But in out policy, I have to ssh successfully to a terminal server first, then from this one, ssh to network device. In Python, I use Paramiko :
import paramiko
ssh = paramiko.SSHClient()
print("OTP : ")
otp = raw_input()
ssh.port=9922
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.load_system_host_keys()
ssh.connect('10.0.0.1',9922,username='khangtt',password=str('12345')+str(otp))
stdin, stdout, stderr = ssh.exec_command('whoami')
stdin.close()
for line in stdout.read().splitlines():
print(line)
Connect to server sucessfully, I can see my username in the output. But I don't know how to SSH to device. I used this but nothing happen to set input user/pass :
stdin, stdout, stderr = ssh.exec_command('telnet 10.80.1.120')
stdin.close()
for line in stdout.read().splitlines():
print(line)

Since you are using paramiko, use the documentation here: https://pynet.twb-tech.com/blog/python/paramiko-ssh-part1.html. Its very explicit.
Or you can also try the codes here to connect:
ssh.connect('10.0.0.1', 'khangtt', str('12345')+str(otp), look_for_keys=False, allow_agent=False)
Or
ssh.connect('10.0.0.1', 'khangtt', str('12345')+str(otp))
in case you don't need look for keys and allow agent.

Related

SFTP Connection From Python [duplicate]

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".

Connecting using Python Paramiko through jump host that offers an interactive selection of target servers

I am trying to connect to a server using SSH protocol through a jump server. When I connect through a terminal using a protocol, the jump server opens a shell and asks for a server number from the list of available servers provided, followed by a user or password. Using the library Paramiko.
My code:
import paramiko
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(
hostname="server_ip",
username="user",
password="pass",
look_for_keys=False,
allow_agent=False
)
com='1'
stdin, stdout, stderr = client.exec_command(com)
data = stdout.read() + stderr.read()
print(data.decode('utf-8'))
I get message:
Invalid target.
My shell on the jump server looks like this:
Your jump server probably shows the selection in an interactive shell session only. So you will have to use SSHClient.invoke_shell, what is otherwise not good thing to do when automating a connection.
See also What is the difference between exec_command and send with invoke_shell() on Paramiko?

Paramiko parallel execution to the remote unix hosts

I have a below script which i'm using to execute commands on remote hosts as a cetralized user, but this script is reads the host file and execute the command one by one however it also remains on the session until its not unlinked from the shell, Hence i want to have a parallel execution saying that when running the script it should be able to fork multiple ssh connection and login to the host and exit immeadiaely after command execution.
Please let me know if you guys have any trick or expert inputs. Though i'm using paramiko as these hosta rae legarcy UNIX hosts where i'm unable to use ansible or like utilities due to some restrictions.
import paramiko
with open('/data/CR9432/SunOS.txt', 'r') as f:
for host in f:
remote_host = host.rstrip()
remote_pass = "pass123"
smart_user = "mtrooper"
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(remote_host, username=smart_user, password=remote_pass)
transport = ssh.get_transport()
session = transport.open_session()
session.set_combine_stderr(True)
session.get_pty()
#for testing purposes we want to force sudo to always to ask for password. because of that we use "-k" key
############################################
#session.exec_command("shutdown -y -i5 -g0")
############################################
stdin = session.makefile('wb', -1)
stdout = session.makefile('rb', -1)
#you have to check if you really need to send password here
stdin.write(remote_pass +'\n')
stdin.flush()
print"\n"
print "------------------------------------------------------------------------------"
print "Command Execution Output On Hostname: "
print "------------------------------------------------------------------------------"
for line in stdout.read().splitlines():
print 'host: %s: %s' % (remote_host, line)

Making SSH from a jumpserver(linux) to Devices(modem) using Python

I'm trying to execute few commands in a Jump server(linux) to access certain devices(modems) using SSH. And then get some device details after login in to the device(modem)
I'm using Paramiko to access jump server, the below code
import paramiko
import time
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('jump server ip', username='user', password='pass', key_filename='D:\New folder\id_rsa')
stdin, stdout, stderr = ssh.exec_command('pwd') #prints the correct pwd
This works fine
So from the jump server I need to ssh a device(modem) using its ipv6 mac address.
the command is
sudo stbsshv6 'ipv6address'/n
But when I execute any command after ssh the device(modem), I'm not getting anything in stdout. Example:
import paramiko
import time
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('jump server ip', username='user', password='pass', key_filename='D:\New folder\id_rsa')
stdin, stdout, stderr = ssh.exec_command('sudo stbsshv6 "ipv6address"')
stdin.write('ifconfig wlan0\n')#some working command
print stdout.readlines() # prints nothing
I can do manually the above steps using putty,
I'm new to python, can anyone suggest the right solution for this or any alternate way is also great. Thanks

Opening more pipes over Paramiko Channel

When connecting to a ssh server via Paramiko, reading the stdios is very easy when using SSHClient.
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('127.0.0.1', username='rusername', password='password')
stdin, stdout, stderr = client.exec_command(cmd)
I can access the used Channel via client.get_transport()._channels (maybe there is better way?)
Is it possible to open more pipes over this channel? I am calling a Python script on the ssh server so I can open the fd in the server side script for writing.
Channel.makefile() doesn't seem to correlate to another pipe/fd in the little testing I've done. I might be misunderstanding the documentation.
To open a file (for reading or writing) on the remote server you can use open_sftp:
sftp = client.open_sftp()
with sftp.open("/tmp/somefile", "w") as outfile:
outfile.write("my data")

Categories