Python implements remote ssh connection linux management and upload file paramiko

Introduction of paramiko Module

"Paramiko" is a combination of "paranoia" and "friend" in Esperanto. It is a module of Python 2.7/3.4 + and implements SSH2 protocol for secure (encryption and authentication) connections to remote machines. Unlike SSL (also known as TLS), SSH2 does not require a strong central authority to sign hierarchical certificates. You may know that SSH2 is a protocol that replaces Telnet and rsh for secure access to remote shell s, but it also includes the ability to open arbitrary channels for remote services through encrypted tunnels (for example, how SFTP works).

Simply put: I want to use python to operate remote Linux servers, or remote machines with ssh services. Through python to view the remote system information locally, execute some instructions, and we can upload or download files.

The goal of this section is to deploy tasks remotely and execute scripts regularly.

I. Installation of paramiko Module

Installation is super simple:

General direct: pip install paramiko

Installation in pycharm is simpler and more user-friendly:

PyCharm Preferences Project: Project Name Project Interpreter

Click + to search for paramiko installation

 

2. Functions of paramiko Foundation and Implementation of dome

1. sshclient login based on username and password

  • Instantiate an SSH object: ssh = paramiko.SSHClient()
  • Automatic Add Machine (otherwise not connected): ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  • Connection server: ssh. connect (hostname=', port=, username=', password=')
  • Execute commands: stdin, stdout, stderr = ssh.exec_command('command'), return three results: standard input, output, error
  • Get the output: result = stdout.read()
  • Close SSH: ssh.close()

What is noticed here is the issue of user permissions, some commands are not executable.

import paramiko

#Create ssh connection objects
ssh=paramiko.SSHClient()
# Allow connections to hosts that are not in the know_hosts file
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# Connecting servers
ssh.connect(hostname='', port=22, username='', password='')
# Execution of orders
stdin, stdout, stderr = ssh.exec_command('df')
# Get command results
res,err = stdout.read(),stderr.read()
result = res if res else err
print(result.decode())
# Close the connection
ssh.close()

2. transport login based on username and password

SSH Client is a traditional operation of connecting servers, executing commands and shutting down. Sometimes it is necessary to log on to the server to perform multiple operations, such as executing commands, uploading/downloading files. The above method can not be implemented. It can be operated in the following ways.

#SSHClient encapsulates Transport
import paramiko
# Instantiate a transport object
transport = paramiko.Transport(('', 22))
# Establish a connection
transport.connect(username='', password='')
# Specify the transport of sshclient's object as the transport above
ssh = paramiko.SSHClient()
ssh._transport = transport
# Executing commands, like traditional methods
stdin, stdout, stderr = ssh.exec_command('df')
print (stdout.read().decode())
# Close the connection
transport.close()

3. File upload and download using transport

import paramiko
# item base trans object# Instantiate a transport object
transport = paramiko.Transport(('',22 ))
# Establish a connection
transport.connect(username='', password='')
# Instantiate an sftp object, specifying the channel for the connection
sftp = paramiko.SFTPClient.from_transport(transport)
 
# LocalFile.txt uploaded to server/home/fishman/test/remote.txt
sftp.put('LocalFile.txt', '/home/fishman/test/remote.txt')
# Download LinuxFile.txt to the local fromlinux.txt file
sftp.get('/home/fishman/test/LinuxFile.txt', 'fromlinux.txt')
transport.close()

3. Realization of Remote Deployment Tasks

def runSshCmd(cmd,*userinof):
    ip=userinof[0]
    name=userinof[1]
    pwd=userinof[2]
    transport = paramiko.Transport((ip, 22))
    # Establish a connection
    transport.connect(username=name, password=pwd)
    # Specify the transport of sshclient's object as the transport above
    ssh = paramiko.SSHClient()
    ssh._transport = transport
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    # Execution of orders
    stdin, stdout, stderr = ssh.exec_command(cmd)
    # Get command results
    res,err = stdout.read(),stderr.read()
    result = res if res else err
    print(result.decode())
    # Close the connection
    ssh.close()
    transport.close()
    
def putfile(inpath,outpath,*userinof):
    ip=userinof[0]
    name=userinof[1]
    pwd=userinof[2]
    transport = paramiko.Transport((ip, 22))
    # Establish a connection
    transport.connect(username=name, password=pwd)
    # Specify the transport of sshclient's object as the transport above
    ssh = paramiko.SSHClient()
    sftp = paramiko.SFTPClient.from_transport(transport)
    # LocalFile.txt uploaded to server/home/fishman/test/remote.txt
    sftp.put(inpath, outpath)
    transport.close()
    
def getfile(inpath,outpath,*userinof):
    ip=userinof[0]
    name=userinof[1]
    pwd=userinof[2]
    transport = paramiko.Transport((ip, 22))
    # Establish a connection
    transport.connect(username=name, password=pwd)
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    sftp = paramiko.SFTPClient.from_transport(transport)
    # Download LinuxFile.txt to the local fromlinux.txt file
    sftp.get(outpath,inpath)
    transport.close()
    
def newcrontab(crontabstr,ip,name,pwd):
    crontabstr="""echo "0 */1 * * * python /home/kt/getPm/CityDataSpider.py" >> /var/spool/cron/root """
    runSshCmd(crontabstr,ip,name,pwd)
def linDeploy(ip,name,pwd):
    putfile(inpath,outpath,*userinof)
    crontabstr=""
    runSshCmd(crontabstr,ip.name,pwd)

 

Tags: ssh sftp Python Pycharm

Posted on Thu, 01 Aug 2019 00:06:13 -0700 by k3Bobos