Ciao, 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. Thanks for support.
CodePudding user response:
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)
CodePudding user response:
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.