pyhon项目之后pexpect使用

pyhon项目之后pexpect使用
1.安装
pip3.6 install pexpect

实例1 ssh 登陆linux 服务器,并且执行命令

#!/usr/bin/env python3.6
# -*- coding: utf-8 -*-
# @Time : 2019/10/24 17:33
# @Author : zoulixiang
# @Site :
# @File : ssh_login_password.py
# @Software: PyCharm
import pexpect

def login_ssh_passwd(port="",user="",host="",passwd="",command=""):
'''函数:用于实现pexepect实现ssh的自动化用户密码登陆'''

#print 'ssh -p %s %s@%s' %(port, user, host)
if port and user and host and passwd and command:
ssh = pexpect.spawn('ssh -p %s %s@%s %s' %(port, user, host, command))
i = ssh.expect(['password:', 'continue connecting (yes/no)?'], timeout=5)
if i == 0:
ssh.sendline(passwd)
elif i == 1:
ssh.sendline('yes\n')
ssh.expect('password: ')
ssh.sendline(passwd)

index = ssh.expect(["#",pexpect.EOF, pexpect.TIMEOUT])

if index == 0:
print("logging in as root!")
#执行命令
ssh.before,ssh.after
elif index == 1:
print("logging in as non-root!")
print(ssh.before)
elif index == 2:
print("logging process exit!")
elif index == 3:
print("logging timeout exit")
else:
print("Parameter error!")

def login_ssh_key(keyfile="",user="",host="",port="", command=""):
'''函数:用于实现pexepect实现ssh的自动化密钥登陆'''
if port and user and host and keyfile and command:
ssh = pexpect.spawn('ssh -i %s -p %s %s@%s %s '% (keyfile,port,user,host,command))
i = ssh.expect([pexpect.TIMEOUT,'continue connecting (yes/no)?'], timeout=5)
print("-"*10)
print(i)
if i == 0:
ssh.sendline('yes\n')
index = ssh.expect(["#", pexpect.EOF, pexpect.TIMEOUT])
else:
index = ssh.expect(["#", pexpect.EOF, pexpect.TIMEOUT])
print(index)

if index == 0:
#执行命令
ssh.before,ssh.after
print("logging in as root!")
elif index == 1:
print("logging in as non-root!")
elif index == 2:
print("logging process exit!")
elif index == 3:
print("logging timeout exit")
else:
print("Parameter error!")

 

def main():
'''主函数:实现两种f方法分别登陆'''
#command = "hostname"
#login_ssh_passwd(port='22', user='root',host='192.168.3.201',passwd='matrix@178',command='pwd')
login_ssh_key(keyfile="/root/.ssh/id_rsa",port='22',user='root',host='192.168.3.201', command="mkdir -p /root/test2222")

if __name__ == '__main__':
main()

posted @   Mr.zou  阅读(315)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
历史上的今天:
2018-10-25 shell脚本之基础

点击右上角即可分享
微信分享提示