paramiko of python module

Reference link: https://blog.51cto.com/13885935/2174984?source=dra

paramiko module

paramiko module provides the functions of ssh and sft for remote login server to execute commands and upload and download files. This is a third-party package, which needs to be installed before use.

import paramiko

# ssh root@ip
# Create an ssh object
client = paramiko.SSHClient()

#If you connect a strange IP for the first time, select yes to confirm the connection automatically
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# Connect to server
client.connect(hostname='111.231.215.66',port=22,username='Manually block account number',password='Manual block password')

# Execution operation
stdin,stdout,stderr = client.exec_command('hostname')

# Get command execution results
host = stdout.read().decode('utf-8').strip()
print(host)

while True:
    command = input("[root@%s]# " %host)
    if command == 'exit()':
        break
    else:
        r = client.exec_command(command)[1].read().decode('utf-8')
        print(r)

# Close connection
client.close()

Example 1:

Connect all hosts in file host information.txt

Unable to connect return connection failure, successful connection, return its host name
Write the connection to a file.

import paramiko

client = paramiko.SSHClient()

client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

def ssh_info(ip,port=22,user='root',passwd='westos'):
    try:
        client.connect(hostname=ip,port=port,username=user,password=passwd)
        r = client.exec_command('hostname')[1].read().decode('utf-8')
    except:
        print('connection failed......')
        return 'connection failed......'
    else:
        client.close()
        print('Successful connection......','\n Host name:%s' %r)
        return 'Successful connection......'+'\n Host name:%s' %r

with open('Connection status.txt','w') as f,open('Host information.txt') as p:
    for line in p:
        line = line.strip()
        ip, port, user, passwd = line.split(':')
        s = ' on connection%s '.center(30, '+') % ip
        f.write(s+'\n')
        f.write(ssh_info(ip,port,user,passwd)+'\n')

Example 2:

Bulk connection based on public key and private key

import paramiko

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

def ssh_info(ip,pkey,port=22,user='root'):
    try:
        print(' on connection%s '.center(30, '+') % ip)
        client.connect(hostname=ip,port=port,username=user,pkey=pkey)
        r = client.exec_command('hostname')[1].read().decode('utf-8')
    except:
        print('connection failed......')
    else:
        client.close()
        print('Successful connection......','\n Host name:%s' %r)

pkey = paramiko.RSAKey.from_private_key_file('id_rsa')

for i in range(254):
    ip = '172.25.254.'+str(i+1)
    ssh_info(ip,pkey)

Example 3:

Upload and download based on public key and private key

import  paramiko

private_key = paramiko.RSAKey.from_private_key_file('id_rsa')

transport = paramiko.Transport(('172.25.254.39', 22))
transport.connect(username='root',pkey=private_key)
sftp = paramiko.SFTPClient.from_transport(transport)

#Download on upper Chuan
sftp.put('/tmp/kiosk', '/mnt/kiosk2')
sftp.get('/mnt/kiosk2', '/home/kiosk/Desktop/day18/kiosk')

transport.close()

Example 1 of paramiko comprehensive exercise

import os
import paramiko

group = [file.rstrip('.conf') for file in os.listdir('host')]
print('Host group'.center(30,'+'))
for i,g in enumerate(group):
    print('\t',str(i+1),'\t',g)
choice = input('Select Action Group:')

print('Host'.center(30,'+'))
host_info_list = []     # Host information in storage file
file = 'host/'+choice+'.conf'
with open(file) as f:
    for line in f:
        line =line.split(':')
        print('\t',line[0])
        host_info_list.append(line)

def do_cmd(cmd,hostname,port=22, username='root', password='westos'):
    print('Connect host ',hostname)
    try:
        client.connect(hostname, port, username, password)
        stdin, stdout, stderr = client.exec_command(cmd)
        result = stdout.read().decode('utf-8').strip()
    except:
        print('connection failed......')
    else:
        client.close()
        print(result)

def get_put(cmd,hostname,port=22, username='root', password='westos'):
    print('Connect host ', hostname)
    try:
        transport = paramiko.Transport((hostname, int(port)))
        transport.connect(username=username, password=password)
        sftp = paramiko.SFTPClient.from_transport(transport)
    except:
        print('connection failed......')
    else:
        # Download on upper Chuan
        if cmd[0] == 'put':
            sftp.put(cmd[1], cmd[2])
            print('Upload success......')
        elif cmd[0] == 'get':
            sftp.get(cmd[1], cmd[2])
            print('Download successful......')
        else:
            print('There is no operation for this command at present......',cmd[0])
        transport.close()

while True:
    cmd = input('>>>: ')
    cmd = cmd.split()
    if cmd == []:
        continue
    elif len(cmd) == 1:
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        for host in host_info_list:
            do_cmd(cmd[0],host[0],host[1],host[2],host[3])
    else:
        for host in host_info_list:
            get_put(cmd,host[0],host[1],host[2],host[3])

paramiko encapsulates instance 1:

import os
import paramiko

class SSH_host:
    def __init__(self,ip,port,u,p,cmd):
        self.ip = ip
        self.port = port
        self.username = u
        self.passwd = p
        self.cmd = cmd

    def cmd(self):
        print('Connect host ',self.ip)
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        try:
            client.connect(self.ip, self.port, self.username, self.passwd)
            stdin, stdout, stderr = client.exec_command(self.cmd[0])
            result = stdout.read().decode('utf-8').strip()
        except:
            print('connection failed......')
        else:
            print(result)
        client.close()

    def get(self):
        print('Connect host ', self.ip)
        try:
            transport = paramiko.Transport((self.ip, self.port))
            transport.connect(self.username, self.passwd)
            sftp = paramiko.SFTPClient.from_transport(transport)
        except:
            print('connection failed......')
        else:
            sftp.get(self.cmd[1], self.cmd[2])
            print('Download successful......')
            transport.close()

    def put(self):
        print('Connect host ', self.ip)
        try:
            transport = paramiko.Transport((self.ip, self.port))
            transport.connect(self.username, self.passwd)
            sftp = paramiko.SFTPClient.from_transport(transport)
        except:
            print('connection failed......')
        else:
            sftp.put(self.cmd[1], self.cmd[2])
            print('Upload success......')
            transport.close()

if __name__ == "__main__":
    group = [file.rstrip('.conf') for file in os.listdir('host')]
    print('Host group'.center(30,'+'))
    for i,g in enumerate(group):
        print('\t',str(i+1),'\t',g)
    choice = input('Select Action Group:')

    print('Host'.center(30,'+'))
    host_info_list = []     # Host information in storage file
    file = 'host/'+choice+'.conf'
    with open(file) as f:
        for line in f:
            line =line.split(':')
            print('\t',line[0])
            host_info_list.append(line)

    while True:
        cmd = input('>>>: ')
        cmd = cmd.split()
        for host in host_info_list:
            link = SSH_host(host[0], int(host[1]), host[2], host[3], cmd)
            if cmd == []:
                continue
            else:
                if hasattr(link, cmd[0]):
                    print(cmd[0])

Tags: sftp ssh

Posted on Sat, 16 Nov 2019 15:38:30 -0500 by darthmahon