模块 paramiko
paramiko是一个用于做远程控制的模块,使用该模块可以对远程服务器进行命令或文件操作,值得一说的是,fabric和ansible内部的远程管理就是使用的paramiko来现实。
1、下载安装
# pycrypto,由于 paramiko 模块内部依赖pycrypto,所以先下载安装pycrypto # 下载安装 pycrypto
wget http://files.cnblogs.com/files/wupeiqi/pycrypto-2.6.1.tar.gz
tar -xvf pycrypto-2.6.1.tar.gz
cd pycrypto-2.6.1
python setup.py build
python setup.py install # 进入python环境,导入Crypto检查是否安装成功 # 下载安装 paramiko
wget http://files.cnblogs.com/files/wupeiqi/paramiko-1.10.1.tar.gz
tar -xvf paramiko-1.10.1.tar.gz
cd paramiko-1.10.1
python setup.py build
python setup.py install
代码远程下载模板
def remote_scp(host_ip,remote_path,local_path,username,password): t = paramiko.Transport((host_ip,22)) t.connect(username=username, password=password) # 登录远程服务器 sftp = paramiko.SFTPClient.from_transport(t) # sftp传输协议 src = remote_path des = local_path sftp.get(src,des) t.close()
远程执行命令 通过用户名密码
#!/usr/bin/env python
#coding:utf-8 import paramiko ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('ip address', 22, 'user', 'passwd')
stdin, stdout, stderr = ssh.exec_command('df')
print stdout.read()
ssh.close();
执行命令
远程执行命令 通过秘钥
import paramiko private_key_path = '/home/auto/.ssh/id_rsa'
key = paramiko.RSAKey.from_private_key_file(private_key_path) ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('主机名 ', 端口, '用户名', key) stdin, stdout, stderr = ssh.exec_command('df')
print stdout.read()
ssh.close()
秘钥执行命令
上传下载
import os,sys
import paramiko t = paramiko.Transport(('182.92.219.86',22))
t.connect(username='wupeiqi',password='')
sftp = paramiko.SFTPClient.from_transport(t)
sftp.put('/tmp/test.py','/tmp/test.py')
t.close() import os,sys
import paramiko t = paramiko.Transport(('182.92.219.86',22))
t.connect(username='wupeiqi',password='')
sftp = paramiko.SFTPClient.from_transport(t)
sftp.get('/tmp/test.py','/tmp/test2.py')
t.close()
上传或者下载文件 - 通过用户名和密码
import paramiko pravie_key_path = '/home/auto/.ssh/id_rsa'
key = paramiko.RSAKey.from_private_key_file(pravie_key_path) t = paramiko.Transport(('182.92.219.86',22))
t.connect(username='wupeiqi',pkey=key) sftp = paramiko.SFTPClient.from_transport(t)
sftp.put('/tmp/test3.py','/tmp/test3.py') t.close() import paramiko pravie_key_path = '/home/auto/.ssh/id_rsa'
key = paramiko.RSAKey.from_private_key_file(pravie_key_path) t = paramiko.Transport(('182.92.219.86',22))
t.connect(username='wupeiqi',pkey=key) sftp = paramiko.SFTPClient.from_transport(t)
sftp.get('/tmp/test3.py','/tmp/test4.py') t.close()
上传或下载文件 - 通过密钥
实战:
公司发布代码更新服务器 远程部署 代码编写
#!/usr/bin/env python
#_*_ coding:utf-8 _*_
__author__ = 'yiyezi'
#导入模块
import os
import sys
import paramiko
import time
import re
#相应目录变量
bak_cmd = 'tar zcvf /backup/web.tar.gz'
wget_dir = '/update'
download = 'http://192.168.1.19/'
app_dir = '/application/data'
app_data = '/application/data/*'
bak_time = time.strftime('%Y_%m_%d_%H:%M:%S')
bak = bak_cmd + bak_time #ssh远程连接
def ssh(ip,port,username,passwd,cmd):
paramiko.util.log_to_file('/tmp/test')
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip, port, username, passwd)
stdin, stdout, stderr = ssh.exec_command(cmd)
print stdout.read()
ssh.close();
#部署
def app(apps):
appname = re.split('\d',apps)
if '.war' in apps:
de_cmd = "cd %s; %s %s;wget %s%s;rm -rf %s;unzip %s -d %s;/bin/sh /scripts/reboot.sh;" % (app_dir,bak,app_data,download,apps,appname[0],apps,appname[0])
print (de_cmd)
elif 'tar.gz' in apps:
de_cmd = "cd %s;%s %s;wget %s%s;rm -rf %s;tar zxvf *.tar.gz;sh /scripts/restart.sh;" %(app_dir,bak,app_data,download,apps,appname[0])
else:
print ("请输入正确的包!")
sys.exit()
ssh("192.168.1.19",22,'root','',de_cmd)
print ('==========================END========================================') def web(apps):
appname = re.split('-\d',apps)
if '.war' in apps:
de_cmd = "cd %s; %s %s;wget %s%s;rm -rf %s;unzip %s -d %s;/bin/sh /scripts/reboot.sh;" % (app_dir,bak,app_data,download,apps,appname[0],apps,appname[0])
print (de_cmd) elif 'tar.gz' in apps:
de_cmd = "cd %s;%s %s;wget %s%s;rm -rf %s;tar zxvf *.tar.gz;sh /scripts/restart.sh;" %(app_dir,bak,app_data,download,apps,appname[0]) else:
print ("请输入正确的包!")
sys.exit()
ssh("192.168.1.11",22,'root','',de_cmd)
print ('==========================END========================================') IP = ["192.168.1.11","192.168.1.19"] def information():
msg = '''
\33[35m----------------------select server update---------------------\033[0m
+ 服务器编号 IP 应用
+ 1 %s web
+ 2 %s app
\33[35m---------------------------------------------------------------\033[0m
'''% (IP[0],IP[1])
print(msg) if __name__ == '__main__':
information()
while True:
num = raw_input("\033[34m请输入你要更新的服务器编号 例如 1 >>\033[0m")
if num == '':
print('\033[32m----------------------------------Update scripts start,please wait....................\033[0m')
time.sleep(5) web("web-2020.tar.gz")
print('\033[32m----------------------------------update Success!--------------------------------------\033[0m')
break
elif num == '':
print('\033[32m----------------------------------Update scripts start,please wait....................\033[0m')
time.sleep(5)
app("web.war")
print('\033[32m----------------------------------update Success!--------------------------------------\033[0m')
break
elif len(num) == 0:
os.system("echo -e '\07'")
print("\033[5;31m输入有误!请重新输入\033[0m")
else:
os.system("echo -e '\07'")
print("\033[5;31m请输入正确的编号\033[0m")