How Do I Start An SSH Session Locally Using Python?
What I mean to ask is, if I am on System 'A' (Linux) and I want to ssh into System 'B' (Windows): On System 'A', I can do ssh admin@xx.xx.xx.xx which will prompt me to a password a
Solution 1:
I generally do it with Paramiko, its easier
import paramiko
# ssh
print 'enter ssh'
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # this will automatically add the keys
ssh.connect(machineHostName, username=user, password=password)
# Run your commands
# example 1 : ls command
print 'do a ls command'
stdin, stdout, stderr = ssh.exec_command('ls')
print stdout.readlines()
time.sleep(2)
# example 2 : change ip address
print 'changing ip address'
stdin, stdout, stderr = ssh.exec_command('sed -i -- s/'+oldIp+'/'+newIp+'/g /etc/sysconfig/network-scripts/ifcfg-eth0')
print stdout.readlines()
time.sleep(2)
To install Paramiko, you can download the tar.gz file from here.
Assuming you are really new to python, how to install this :
- Download the
tar.gz
file - Extract the contents to a folder
cd
into that extracted folder, from your terminal- execute this
python setup.py install
- then you can try something like the above example
NOTE : if you get stuck with installation comment here, and I can help you.
Solution 2:
Instead of using a passphrase for authentication, you could use ssh keys as described here.
Start your ssh client on System "A" using
subprocess.call(['/path/to/ssh', 'admin@xx.xx.xx.xx', 'remote_script.sh'])
Post a Comment for "How Do I Start An SSH Session Locally Using Python?"