您的位置:首页 > 运维架构 > Shell

Python免秘钥ssh远程登录执行命令and本地执行shell命令

2018-01-04 11:14 926 查看

python远程执行

python paramiko 模块的应用

环境

# yum install python-dev
# yum install python-devel
# pip install pycrypto
# pip install paramiko
# pip install ssh


方法体

import paramiko
def DiskCheck(ip):
try:
# 建立一个sshclient对象
ssh = paramiko.SSHClient()
# 允许将信任的主机自动加入到host_allow 列表,此方法必须放在connect方法的前面
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 指定本地的RSA私钥文件,如果建立密钥对时设置的有密码,password为设定的密码,如无不用指定password参数
# pkey = paramiko.RSAKey.from_private_key_file('/home/super/.ssh/id_rsa', password='12345')
pkey = paramiko.RSAKey.from_private_key_file('/home/ptop/topicjie/scripts/keys/id_rsa')
# 建立连接
ssh.connect(hostname=ip,
port=22,
username='ptop',
pkey=pkey)
# 执行命令
stdin, stdout, stderr = ssh.exec_command("for i in $(df -h|grep data|awk '{print $6}'); do  touch $i/test.txt; done; df -h|grep data")
# 结果放到stdout中,如果有错误将放到stderr中
print(stdout.read().decode())
print(stderr.read())
# 关闭连接
ssh.close()


提示:最好采用ssh免秘钥登录的模式,尽量不要出现明文密码

本机执行shell脚本

python中有很多调用本地shell脚本的方法 类似commands 等,不过现在官方推荐的是使用subprocess 进行本地shell脚本的调用,这个模块的方法较多。

import shlex
import subprocess

def execute_command(cmdstring, cwd=None, timeout=None, shell=False):
if shell:
cmdstring_list = cmdstring
else:
cmdstring_list = shlex.split(cmdstring)
if timeout:
end_time = datetime.datetime.now() + datetime.timedelta(seconds=timeout)
#没有指定标准输出和错误输出的管道,因此会打印到屏幕上;
sub = subprocess.Popen(cmdstring_list, cwd=cwd, stdin=subprocess.PIPE,shell=shell,bufsize=4096)
#subprocess.poll()方法:检查子进程是否结束了,如果结束了,设定并返回码,放在subprocess.returncode变量中
while sub.poll() is None:
time.sleep(0.1)
if timeout:
if end_time <= datetime.datetime.now():
raise Exception("Timeout:%s"%cmdstring)

return str(sub.returncode)
#方法测试
p=execute_command("hive -f "+path)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: