0

I want to connect via ssh using python. I've tried this command: os.system("cmd /k root@ip) and it worked well. the problem is that after this a password is required and it is not clear to me which command shall I use. Furthermore I noticed that the os.system command stay "alive" and doesn't allow the code to go on the next step until the shell is not closed.

Inuyasha84
  • 50
  • 9

2 Answers2

3

Have you tried using paramiko?

import paramiko

ssh_client = paramiko.SSHClient()
ssh_client .connect(server, username=username, password=password)
stdin, stdout, stderr = ssh_client.exec_command(command)
Adid
  • 1,504
  • 3
  • 13
  • Ciao, I've exstablish an SSH connection using the following code: > session = myconn.connect(SIM_IP, username =USER_SIM, password=PSW_SIM) > stdin, stdout, stderr = myconn.exec_command(prova_comando) > lines=stdout.readlines() print(lines) now I want from this SSH, connect to another SSH which need the password as the previous one. How can I do this? Thanks – Inuyasha84 Jun 07 '22 at 12:59
  • @Inuyasha84 this should be helpful: https://stackoverflow.com/questions/35304525/nested-ssh-using-python-paramiko – Prashant Maurya Jun 20 '22 at 08:57
0

You can use pexpect's pxssh module to connect to ssh and run command:

from pexpect import pxssh
import getpass
try:
    ssh_cmd = pxssh.pxssh()
    hostname = raw_input('hostname: ')
    username = raw_input('username: ')
    password = getpass.getpass('password: ')
    ssh_cmd.login(hostname, username, password)
    ssh_cmd.sendline('df -hT')   # run a command(you can specify any command here)
    ssh_cmd.prompt()             # match the prompt
    print(ssh_cmd.before)        # print everything before the prompt
    ssh_cmd.logout()
except pxssh.ExceptionPxssh as e:
    print("SSH login Failed")
    print(e)

For more details you can refer pxssh documentation.

Prashant Maurya
  • 639
  • 4
  • 13