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()
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .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脚本之基础