Python学习—paramiko模块实现简单的ssh与sftp-创新互联-成都快上网建站

Python学习—paramiko模块实现简单的ssh与sftp-创新互联

paramiko模块

paramiko模块提供了ssh及sft进行远程登录服务器执行命令和上传下载文件的功能。这是一个第三方的软件包,使用之前需要安装。

创新互联建站主营青阳网站建设的网络公司,主营网站建设方案,重庆App定制开发,青阳h5成都小程序开发搭建,青阳网站营销推广欢迎青阳等地区企业咨询
import paramiko

# ssh root@ip
# 创建一个ssh对象
client = paramiko.SSHClient()

#如果第一次连接陌生的IP,自动选择yes确认连接
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# 连接服务器
client.connect(hostname='111.231.215.66',port=22,username='手动屏蔽帐号',password='手动屏蔽密码')

# 执行操作
stdin,stdout,stderr = client.exec_command('hostname')

# 获取命令执行结果
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)

# 关闭连接
client.close()

Python学习—paramiko模块实现简单的ssh与sftp

例子1:

连接文件 主机信息.txt 中的所有主机
Python学习—paramiko模块实现简单的ssh与sftp
不能连接返回连接失败,成功连接,返回其主机名
把连接情况写入文件。

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('连接失败......')
        return '连接失败......'
    else:
        client.close()
        print('连接成功......','\n主机名:%s' %r)
        return '连接成功......'+'\n主机名:%s' %r

with open('连接状况.txt','w') as f,open('主机信息.txt') as p:
    for line in p:
        line = line.strip()
        ip, port, user, passwd = line.split(':')
        s = ' 正在连接%s '.center(30, '+') % ip
        f.write(s+'\n')
        f.write(ssh_info(ip,port,user,passwd)+'\n')

Python学习—paramiko模块实现简单的ssh与sftp

例子2:

基于公钥私钥的批量连接

import paramiko

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

def ssh_info(ip,pkey,port=22,user='root'):
    try:
        print(' 正在连接%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('连接失败......')
    else:
        client.close()
        print('连接成功......','\n主机名:%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)

例子3:

基于公钥私钥的上传下载

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)

#上川下载
sftp.put('/tmp/kiosk', '/mnt/kiosk2')
sftp.get('/mnt/kiosk2', '/home/kiosk/Desktop/day18/kiosk')

transport.close()

paramiko综合练习实例1

import os
import paramiko

group = [file.rstrip('.conf') for file in os.listdir('host')]
print('主机组'.center(30,'+'))
for i,g in enumerate(group):
    print('\t',str(i+1),'\t',g)
choice = input('选择操作组:')

print('主机'.center(30,'+'))
host_info_list = []     # 存储文件中主机信息
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('连接主机 ',hostname)
    try:
        client.connect(hostname, port, username, password)
        stdin, stdout, stderr = client.exec_command(cmd)
        result = stdout.read().decode('utf-8').strip()
    except:
        print('连接失败......')
    else:
        client.close()
        print(result)

def get_put(cmd,hostname,port=22, username='root', password='westos'):
    print('连接主机 ', hostname)
    try:
        transport = paramiko.Transport((hostname, int(port)))
        transport.connect(username=username, password=password)
        sftp = paramiko.SFTPClient.from_transport(transport)
    except:
        print('连接失败......')
    else:
        # 上川下载
        if cmd[0] == 'put':
            sftp.put(cmd[1], cmd[2])
            print('上传成功......')
        elif cmd[0] == 'get':
            sftp.get(cmd[1], cmd[2])
            print('下载成功......')
        else:
            print('暂时没有这个命令的操作......',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封装实例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('连接主机 ',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('连接失败......')
        else:
            print(result)
        client.close()

    def get(self):
        print('连接主机 ', self.ip)
        try:
            transport = paramiko.Transport((self.ip, self.port))
            transport.connect(self.username, self.passwd)
            sftp = paramiko.SFTPClient.from_transport(transport)
        except:
            print('连接失败......')
        else:
            sftp.get(self.cmd[1], self.cmd[2])
            print('下载成功......')
            transport.close()

    def put(self):
        print('连接主机 ', self.ip)
        try:
            transport = paramiko.Transport((self.ip, self.port))
            transport.connect(self.username, self.passwd)
            sftp = paramiko.SFTPClient.from_transport(transport)
        except:
            print('连接失败......')
        else:
            sftp.put(self.cmd[1], self.cmd[2])
            print('上传成功......')
            transport.close()

if __name__ == "__main__":
    group = [file.rstrip('.conf') for file in os.listdir('host')]
    print('主机组'.center(30,'+'))
    for i,g in enumerate(group):
        print('\t',str(i+1),'\t',g)
    choice = input('选择操作组:')

    print('主机'.center(30,'+'))
    host_info_list = []     # 存储文件中主机信息
    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])

Python学习—paramiko模块实现简单的ssh与sftp

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


分享题目:Python学习—paramiko模块实现简单的ssh与sftp-创新互联
链接地址:http://kswjz.com/article/hocsd.html
扫二维码与项目经理沟通

我们在微信上24小时期待你的声音

解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流