This example imports the getpass module, which will prompt the host, user, and password, establish the connection, and run some commands on a remote server.
You can find the following code in the filename: pxsshConnection.py:
import pxssh
import getpass
try:
connection = pxssh.pxssh()
hostname = input('hostname: ')
username = input('username: ')
password = getpass.getpass('password: ')
connection.login (hostname, username, password)
connection.sendline ('ls -l')
connection.prompt()
print(connection.before)
connection.sendline ('df')
connection.prompt()
print(connection.before)
connection.logout()
except pxssh.ExceptionPxssh as e:
print("pxssh failed on login.")
print(str(e))
We can create specific methods to establish the connection and send commands.
You can find the following code in the filename: pxsshCommand.py:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import pxssh
hostname = 'localhost'
user = 'user'
password = 'password'
command = 'df -h'
def send_command(ssh_session, command):
ssh_session.sendline(command)
ssh_session.prompt()
print(ssh_session.before)
def connect(hostname, username, password):
try:
s = pxssh.pxssh()
if not s.login(hostname, username, password):
print("SSH session failed on login.")
return s
except pxssh.ExceptionPxssh as e:
print('[-] Error Connecting')
print(str(e))
def main():
session = connect(host, user, password)
send_command(session, command)
session.logout()
if __name__ == '__main__':
main()