如何远程登录Linuxev3魔方机器人程序并运行Python程序

Python操作远程服务器切换到root用户_Linux编程_Linux公社-Linux系统门户网站
你好,游客
Python操作远程服务器切换到root用户
来源:Linux社区&
作者:Linux
在自动化运维过程中,需要远程服务器切换到root用户下执行命令,尝试了一些方法,得到如下好用的方法,供大家使用:
import time import paramiko & def verification_ssh(host,username,password,port,root_pwd,cmd): & & s=paramiko.SSHClient()&
& & s.load_system_host_keys()&
& & s.set_missing_host_key_policy(paramiko.AutoAddPolicy()) & & s.connect(hostname = host,port=int(port),username=username, password=password) & & if username != 'root': & & & & ssh = s.invoke_shell() & & & & time.sleep(0.1) & & & & ssh.send('su - \n') & & & & buff = '' & & & & while not buff.endswith('Password: '): & & & & & & resp = ssh.recv(9999) & & & & & & buff +=resp & & & & ssh.send(root_pwd) & & & & ssh.send('\n') & & & & buff = '' & & & & while not buff.endswith('# '): & & & & & & resp = ssh.recv(9999) & & & & & & buff +=resp & & & & ssh.send(cmd) & & & & ssh.send('\n') & & & & buff = '' & & & & while not buff.endswith('# '): & & & & & & resp = ssh.recv(9999) & & & & & & buff +=resp & & & & s.close() & & & & result = buff& & else: & & & & stdin, stdout, stderr = s.exec_command(cmd) & & & & result = stdout.read() & & & & s.close() & & return result & if __name__ == "main": & & verification_ssh('192.168.1.11','cimer','1q2w3e4r',22,'1q2w3e4r','ifdown eth0')
本文永久更新链接地址:
相关资讯 & & &
   同意评论声明
   发表
尊重网上道德,遵守中华人民共和国的各项有关法律法规
承担一切因您的行为而直接或间接导致的民事或刑事法律责任
本站管理人员有权保留或删除其管辖留言中的任意内容
本站有权在网站内转载或引用您的评论
参与本评论即表明您已经阅读并接受上述条款用python写个自动SSH登录远程服务器的小工具(实例)
投稿:jingxian
字体:[ ] 类型:转载 时间:
下面小编就为大家带来一篇用python写个自动SSH登录远程服务器的小工具(实例)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
很多时候我们喜欢在自己电脑的终端直接ssh连接Linux服务器,而不喜欢使用那些有UI界面的工具区连接我们的服务器。可是在终端使用ssh我们每次都需要输入账号和密码,这也是一个烦恼,所以我们可以简单的打造一个在Linux/Mac os运行的自动ssh登录远程服务器的小工具。
来个GIF动画示例下先:
我们先理一下我们需要些什么功能:
1. 添加/删除连接服务器需要的IP,端口,密码
2. 自动输入密码登录远程服务器
对,我们就做这么简单的功能
开始写代码
代码比较长,所以我也放在在Github和码云,地址在文章最底部:
1.我们建个模块目录osnssh(Open source noob ssh),然后在下面再建两个目录,一个用来放主程序取名叫bin吧,一个用来保存登录数据(IP, 端口,密码)叫data吧。
1.设置程序:添加/删除IP,端口,密码. 建立py文件bin/setting.py:
#!/usr/bin/env python
#-*-coding:utf-8-*-
import re, base64, os, sys
path = os.path.dirname(os.path.abspath(sys.argv[0]))
选项配置管理
__author__ = 'allen woo'
def add_host_main():
if add_host():
print("\n\nAgain:")
def add_host():
添加主机信息
print("================Add=====================")
print("[Help]Input '#q' exit")
host_ip = str_format("Host IP:", "^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$")
if host_ip == "#q":
# 输入端口
host_port = str_format("Host port(Default 22):", "[0-9]+")
if host_port == "#q":
# 输入密码
password = str_format("Password:", ".*")
if password == "#q":
# 密码加密
password = base64.encodestring(password)
# 输入用户名
name = str_format("User Name:", "^[^ ]+$")
if name == "#q":
elif not name:
os.system("clear")
print("[Warning]:User name cannot be emptyg")
# The alias
# 输入别名
alias = str_format("Local Alias:", "^[^ ]+$")
if alias == "#q":
elif not alias:
os.system("clear")
print("[Warning]:Alias cannot be emptyg")
# 打开数据保存文件
of = open("{}/data/information.d".format(path))
hosts = of.readlines()
# 遍历文件数据,查找是否有存在的Ip,端口,还有别名
for l in hosts:
l = l.strip("\n")
l_list = l.split(" ")
if host_ip == l_list[1] and host_port == l_list[2]:
os.system("clear")
print("[Warning]{}:{} existing".format(host_ip, host_port))
if alias == l_list[4]:
os.system("clear")
print("[Warning]Alias '{}' existing".format(alias))
of.close()
# 保存数据到数据文件
of = open("{}/data/information.d".format(path), "a")
of.write("\n{} {} {} {} {}".format(name.strip("\n"), host_ip.strip("\n"), host_port, password.strip("\n"), alias.strip("\n")))
of.close()
print("Add the success:{} {}@{}:{}".format(alias.strip("\n"), name.strip("\n"), host_ip.strip("\n"), host_port, password.strip("\n")))
def remove_host():
删除主机信息
# 打开数据文件
of = open("{}/data/information.d".format(path))
hosts = of.readlines()
l = len(hosts)
if l &= 0:
os.system("clear")
print("[Warning]There is no host")
print("================Remove================")
print("+{}+".format("-"*40))
Alias UserName@IP:PORT")
hosts_temp = []
# 遍历输出所以信息(除了密码)供选择
for i in range(0, l):
if not hosts[i].strip():
v_list = hosts[i].strip().split(" ")
print("+{}+".format("-"*40))
print("| {} | {} {}@{}:{}".format(n+1, v_list[4], v_list[0], v_list[1], v_list[2]))
hosts_temp.append(hosts[i])
hosts = hosts_temp[:]
print("+{}+".format("-"*40))
c = raw_input("[Remove]Choose the Number or Alias('#q' to exit):")
is_alias = False
is_y = False
c = int(c)
if c & l or c & 1:
os.system("clear")
print("[Warning]:There is no")
del hosts[c-1]
is_y = True
is_alias = True
if is_alias:
if c.strip() == "#q":
os.system("clear")
for l in hosts:
if c.strip() == l.split(" ")[4].strip():
del hosts[n]
is_y = True
if not is_y:
os.system("clear")
print("[Warning]:There is no")
# 再次确认是否删除
c = raw_input("Remove?[y/n]:")
if c.strip().upper() == "Y":
of = open("{}/data/information.d".format(path), "w")
for l in hosts:
of.write(l)
print("Remove the success!")
of.close()
def str_format(lable, rule):
用于验证输入的数据格式
:param lable:
:param rule:
print("{} ('#q' exit)".format(lable))
temp = raw_input().strip()
m = re.match(r"{}".format(rule), temp)
elif "port" in lable:
elif temp.strip() == "#q":
os.system("clear")
os.system("clear")
print("[Warning]:Invalid format")
return temp
2. 我们再添加一个函数在setting.py用于输出我们的信息,也就是about me。
def about():
输出关于这个程序的信息
of = open("{}/bin/about.dat".format(path))
rf = of.read()
info = eval(rf)
os.system("clear")
print("================About osnssh================")
for k,v in info.items():
print("{}: {}".format(k, v))
print("For failure.")
然后在bin目录下面建立个文件about.dat写入我们的一些信息,比如:
"auther":"Allen Woo",
"Introduction":"In Linux or MAC using SSH, do not need to enter the IP and password for many times",
"Home page":"",
"Download address":"/osnoob/osnssh",
"version":"1.1.0",
"email":""
好了设置程序就这样了:
2. 自动登录远程服务器程序:在bin建个py文件叫auto_ssh.py:
注意:这里我们需要先安装个包叫:pexpect, 用户终端交互,捕捉交互信息实现自动输入密码。
安装pexpect:
pip install pexpect
然后开始写代码:
#!/usr/bin/env python
#-*-coding:utf-8-*-
import os, sys, base64
import pexpect
path = os.path.dirname(os.path.abspath(sys.argv[0]))
def choose():
# 打开我们的数据文件
of = open("{}/data/information.d".format(path))
hosts = of.readlines()
hosts_temp = []
for h in hosts:
if h.strip():
hosts_temp.append(h)
hosts = hosts_temp[:]
l = len(hosts)
if l &= 0:
os.system("clear")
print("[Warning]Please add the host server")
print("=================SSH===================")
print("+{}+".format("-"*40))
Alias UserName@IP:PORT")
for i in range(0, l):
v_list = hosts[i].strip().split(" ")
print("+{}+".format("-"*40))
print("| {} | {} {}@{}:{}".format(i+1, v_list[4], v_list[0], v_list[1], v_list[2]))
print("+{}+".format("-"*40))
c = raw_input("[SSH]Choose the number or alias('#q' exit):")
is_alias = False
is_y = False
c = int(c)
if c & l or c & 1:
os.system("clear")
print("[Warning]:There is no")
l_list = hosts[c-1].split(" ")
name = l_list[0]
host = l_list[1]
port = l_list[2]
password = l_list[3]
is_y = True
is_alias = True
if is_alias:
if c.strip() == "#q":
os.system("clear")
for h in hosts:
if c.strip() == h.split(" ")[4].strip():
l_list = h.split(" ")
name = l_list[0]
host = l_list[1]
port = l_list[2]
password = l_list[3]
is_y = True
if not is_y:
# 将加密保存的密码解密
password = base64.decodestring(password)
print("In the connection...")
# 准备远程连接,拼接ip:port
print("{}@{}".format(name, host))
if port == "22":
connection("ssh {}@{}".format(name, host), password)
connection("ssh {}@{}:{}".format(name, host, port), password)
def connection(cmd, pwd):
连接远程服务器
:param cmd:
:param pwd:
child = pexpect.spawn(cmd)
i = child.expect([".*password.*", ".*continue.*?", pexpect.EOF, pexpect.TIMEOUT])
if( i == 0 ):
# 如果交互中出现.*password.*,就是叫我们输入密码
# 我们就把密码自动填入下去
child.sendline("{}\n".format(pwd))
child.interact()
elif( i == 1):
# 如果交互提示是否继续,一般第一次连接时会出现
# 这个时候我们发送"yes",然后再自动输入密码
child.sendline("yes\n")
child.sendline("{}\n".format(pwd))
#child.interact()
# 连接失败
print("[Error]The connection fails")
好了,现在我们只需要启动文件了,也就是打开程序后的第一个菜单
3.再osnssh目录下建个osnssh.py 文件:
#!/usr/bin/env python
#-*-coding:utf-8-*-
import os, sys
sys.path.append("../")
from bin import setting, auto_ssh
path = os.path.dirname(os.path.abspath(sys.argv[0]))
方便在LINUX终端使用ssh,保存使用的IP:PORT , PASSWORD
__author__ = 'allen woo'
def main():
print("==============OSNSSH [Menu]=============")
print("1.Connection between a host\n2.Add host\n3.Remove host\n4.About\n[Help]: q:quit clear:clear screen")
print("="*40)
c = raw_input("Please select a:")
if c == 1 or c == "1":
auto_ssh.choose()
if c == 2 or c == "2":
setting.add_host_main()
if c == 3 or c == "3":
setting.remove_host()
if c == 4 or c == "4":
setting.about()
elif c == "clear":
os.system("clear")
elif c == "q" or c == "Q" or c == "quit":
print("Bye")
sys.exit()
print("\n")
if __name__ == '__main__':
of = open("{}/data/information.d".format(path))
of = open("{}/data/information.d".format(path), "w")
of.close()
终于写完了,我们可以试一试了:
$python osnssh.py
以上这篇用python写个自动SSH登录远程服务器的小工具(实例)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。
您可能感兴趣的文章:
大家感兴趣的内容
12345678910
最近更新的内容
常用在线小工具如何在linux服务器上用 PHP 执行 python 脚本? - 知乎39被浏览9947分享邀请回答3011 条评论分享收藏感谢收起2添加评论分享收藏感谢收起查看更多回答拒绝访问 |
| 百度云加速
请打开cookies.
此网站 () 的管理员禁止了您的访问。原因是您的访问包含了非浏览器特征(3a7d80dce78543bf-ua98).
重新安装浏览器,或使用别的浏览器博客访问: 49351
博文数量: 30
博客积分: 0
博客等级: 民兵
技术积分: 322
注册时间:
IT168企业级官微
微信号:IT168qiye
系统架构师大会
微信号:SACC2013
分类: 系统运维
Python paramiko模块
账号密码登录
&&& import paramiko &
&&& ssh=paramiko.SSHClient() & & & & & & & & & & & & & & & & & & & &
&&& ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
&&& ssh.connect("192.168.0.115","22","root","centos")
&&& stdin,stdout,stderr=ssh.exec_command("hostname")
&&& print stdout.read().strip()
&&& ssh.close()
免秘钥登录
&&& import paramiko
&&& import os
&&& ssh=paramiko.SSHClient()
&&& ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
&&& privatekeyfile = os.path.expanduser('~/.ssh/id_rsa') & & &&#os.path.expanduser把~转换为当前用户,如~/.ssh/id_rsa=/root/.ssh/id_rsa等,也可以直接指定如下:
&&& mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile) &&#mykey=paramiko.RSAKey.from_private_key_file("/root/.ssh/id_rsa") & 这样是可以,但是换user or&server后就会遇到麻烦。
&&& ssh.connect('192.168.0.115', username = 'root', pkey = mykey) & & & &
&&& stdin,stdout,stderr=ssh.exec_command("ifconfig")
&&& print stdout.read().strip() & & ---& 输出命令结果
&&& ssh.close()
上传文件到client
&&& import paramiko & & & & & & & & & & & & & & &
&&& ssh=paramiko.Transport(("192.168.0.115",22))
&&& ssh.connect(username="root",password="centos")
&&& repath="/root/class.py" & & #上传到client path
&&& lopath="/data/py/class.py" &#从lopath上传
&&& sftp=paramiko.SFTPClient.from_transport(ssh) & & & & & & & & & & & &&
&&& sftp.put(lopath,repath) & & & & & & & & & & & & & &&
&SFTPAttributes: [ size=569 uid=0 gid=0 mode=0100644 atime= mtime= ]&
&&& ssh.close()
远程下载文件
&&& import paramiko
&&& ssh=paramiko.Transport(("192.168.0.115",22))
&&& ssh.connect(username="root",password="centos")
&&& repath="/root/class.py"
&&& lopath="/data/py/class.py"
&&& sftp=paramiko.SFTPClient.from_transport(ssh)
&&& sftp.get(repath,lopath)
&&& ssh.close()
远程下载文件 和 上传文件代码只差了sftp.put(lopath,repath) & & sftp.get(repath,lopath) & get和 put的区别
多线程批量处理
#!/usr/bin/python&
import paramiko
import threading
import time
def ssh2(ip,username,passwd,cmd):
& & & & ssh = paramiko.SSHClient()
& & & & ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
& & & & ssh.connect(ip,22,username,passwd,timeout=5)
& & & & for m in cmd:
& & & & & & stdin, stdout, stderr = ssh.exec_command(m)
& & & & & & out = stdout.read(),
& & & & & & for o in out:
& & & & & & & & if not o:
& & & & & & & & & & & & print "error %s" %ip
& & & & & & & & & & & & break
& & & & & & & & print o,
& & & & & & & & print '%s\tOK\n'%(ip)
& & & & ssh.close()
if __name__=='__main__':
& & cmd = ['cal','who','uptime']
& & username = "root"
& & passwd = "centos"
& & threads = [4]
& & file=open("/data/py/host.txt")
& & f=file.read().split()
& & for ip in f:
& & & & a=threading.Thread(target=ssh2,args=(ip,username,passwd,cmd)) & & & & & & &&
& & & & a.start()
& & print "current has %d threads" % (threading.activeCount() - 1)
阅读(3791) | 评论(0) | 转发(0) |
相关热门文章
给主人留下些什么吧!~~
请登录后评论。}

我要回帖

更多关于 64位机器运行32位程序 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信