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)
相关文章推荐
- linux使用Python上秘钥远程登录ssh执行shell命令
- python 使用ssh远程登录并执行命令返回结果
- 用python SSH模块登录,并在远程机执行shell命令
- Python之Fabric模块 Fabric是基于Python实现的SSH命令行工具,简化了SSH的应用程序部署及系统管理任务,它提供了系统基础的操作组件,可以实现本地或远程shell命令,包括:
- shell小白 想玩自动化部署,无密码ssh 登录远程服务器,执行scp命令传送war包 并重启tomcat。
- 用python SSH模块登录,并在远程机执行shell命令
- python SSH模块登录,远程机执行shell命令实例解析
- 利用python的paramiko模块ssh登录本地虚拟机并执行任意命令
- 用python SSH模块登录,并在远程机执行shell命令
- python ssh2远程登录节点并执行命令
- Python实现ssh登录执行shell命令并将结果写入mysql数据库
- shell小白 想玩自动化部署,无密码ssh 登录远程服务器,执行scp命令传送war包 并重启tomcat。
- 用python脚本执行ssh远程登录多台机器
- python批量操作Linux服务器脚本,ssh密码登录(执行命令、上传、下载)(一)
- Windows下通过SSH使用SharpSSH远程登录主机执行命令传输文件
- SSH登录到远程linux机器并执行命令
- 使用ssh远程执行命令批量导出数据库到本地
- Python3之基于tcp模拟ssh远程执行命令
- ssh批量登录并执行命令(python实现)
- erlang 利用 ssh 远程执行 shell 命令