How do I start an SSH session locally using Python

2019-08-01 09:28发布

问题:

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 and when that gets authenticated, I will get to the "$" of System "B" (on System "A").

  1. how do I send username and password together as a single line (since I want to use a script)
  2. How to achieve the scenario that I have above.

回答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.



回答2:

  1. Instead of using a passphrase for authentication, you could use ssh keys as described here.

  2. Start your ssh client on System "A" using subprocess.call(['/path/to/ssh', 'admin@xx.xx.xx.xx', 'remote_script.sh'])