Paramiko
一、安装,下载
1、下载安装 pycrypto-2.6.1.tar.gz (apt-get install python-dev)
解压,进入,python setup.py build【编译】,python setup.py install 【安装】 ----》import Crypto
2、下载安装 paramiko-1.10.1.tar.gz
解压,进入,python setup.py build【编译】,python setup.py install 【安装】---》 import paramiko
二、paramiko 功能
1、连接远程服务器,并执行操作
用户名和密码连接
#!/usr/bin/env python
#coding:utf-8
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('192.168.1.108', 22, 'alex', '123')
stdin, stdout, stderr = ssh.exec_command('df')
print stdout.read()
ssh.close();
2、上传和下载文件
import os,sys
import paramiko
t = paramiko.Transport(('182.92.219.86',22))
t.connect(username='wupeiqi',password='WOshiniba8')
sftp = paramiko.SFTPClient.from_transport(t)
sftp.put('/tmp/test.py','/tmp/test.py')
t.close()
import os,sys
import paramiko
t = paramiko.Transport(('182.92.219.86',22))
t.connect(username='wupeiqi',password='WOshiniba8')
sftp = paramiko.SFTPClient.from_transport(t)
sftp.get('/tmp/test.py','/tmp/test2.py')
t.close()
3.通过SSH连接
ssh-keygen -t rsa
ssh-copy-id -i ~/ssh/id_rsa.pub wupeiqi@192.168.159.129
import paramiko
private_key_path = '/home/auto/.ssh/id_rsa'
key = paramiko.RSAKey.from_private_key_file(private_key_path)
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('182.92.219.96 ', 22, 'wupeiqi', 'xxxx', key)
stdin, stdout, stderr = ssh.exec_command('df')
print stdout.read()
ssh.close();
5.上传和下载文件
import paramiko
pravie_key_path = '/home/auto/.ssh/id_rsa'
key = paramiko.RSAKey.from_private_key_file(pravie_key_path)
t = paramiko.Transport(('182.92.219.86',22))
t.connect(username='wupeiqi',pkey=key)
sftp = paramiko.SFTPClient.from_transport(t)
sftp.put('/tmp/test3.py','/tmp/test3.py')
t.close()
import paramiko
pravie_key_path = '/home/auto/.ssh/id_rsa'
key = paramiko.RSAKey.from_private_key_file(pravie_key_path)
t = paramiko.Transport(('182.92.219.86',22))
t.connect(username='wupeiqi',pkey=key)
sftp = paramiko.SFTPClient.from_transport(t)
sftp.get('/tmp/test3.py','/tmp/test4.py')
t.close()
5、第三种连接
import paramiko
scp = paramiko.Transport(('182.92.219.86',22));
scp.connect(username='wupeiqi',password='xxx');
channel = scp.open_session();
print channel.exec_command('mkdir hello')
channel.close();
scp.close();
6、交互式连接
import paramiko
import interactive
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('192.168.1.108', 22, 'alex', '123')
channel = ssh.invoke_shell()
interactive.interactive_shell(channel)
channel.close()
ssh.close();
7、paramiko的demo.py文件
三、审计系统
需求:记录用户在服务器的所有操作!!
1、需要一台主机当作堡垒机
2、所有用户只能登录堡垒机
3、登录堡垒机后,可以对远程服务器进行操作
4、记录用户的所有操作
【登录堡垒机】--> 【选择服务器】 --> 【操作服务器,并记录操作】
实现:
1、创建堡垒机用户
adduser xxx
2、用户登录堡垒机后,自动执行脚本
配置 .brashrc
添加 /usr/bin/python /home/wupeiqi/share/workspace/07day07/section_two/menu.py
3、堡垒机提示与用户对应的服务器
import os,sys
msg = """
\033[42;1mWelcome using old boy's auditing system!\033[0m
"""
print msg
host_dic = {
'zhangke': '10.0.0.137',
'xiaoqing': '10.0.0.135',
'hanxin' : '10.0.1.139'
}
while True:
for hostname, ip in host_dic.items():
print hostname,ip
try:
host = raw_input('Please choose one server to login:').strip()
if host == 'quit':
print "Goodbye!"
break
except KeyboardInterrupt:continue
except EOFError:continue
if len(host) ==0:continue
if not host_dic.has_key(host) :
print 'No host matched, try again.'
continue
print '\033[32;1mGoing to connect \033[0m', host_dic[host]
os.system("python demo.py %s" % host_dic[host])
4、记录日志
# Copyright (C) 2003-2007 Robey Pointer <robeypointer@gmail.com>
#
# This file is part of paramiko.
#
# Paramiko is free software; you can redistribute it and/or modify it under the
# terms of the GNU Lesser General Public License as published by the Free
# Software Foundation; either version 2.1 of the License, or (at your option)
# any later version.
#
# Paramiko is distrubuted in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Paramiko; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
import socket
import sys
# windows does not have termios...
try:
import termios
import tty
has_termios = True
except ImportError:
has_termios = False
def interactive_shell(chan):
if has_termios:
posix_shell(chan)
else:
windows_shell(chan)
def posix_shell(chan):
import select
oldtty = termios.tcgetattr(sys.stdin)
try:
tty.setraw(sys.stdin.fileno())
tty.setcbreak(sys.stdin.fileno())
chan.settimeout(0.0)
f = file('/tmp/auto.log','a+')
while True:
r, w, e = select.select([chan, sys.stdin], [], [])
if chan in r:
try:
x = chan.recv(1024)
if len(x) == 0:
print '\r\n*** EOF\r\n',
break
sys.stdout.write(x)
sys.stdout.flush()
except socket.timeout:
pass
if sys.stdin in r:
x = sys.stdin.read(1)
f.write(x)
f.flush()
if len(x) == 0:
break
chan.send(x)
f.close()
finally:
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
# thanks to Mike Looijmans for this code
def windows_shell(chan):
import threading
sys.stdout.write("Line-buffered terminal emulation. Press F6 or ^Z to send EOF.\r\n\r\n")
def writeall(sock):
while True:
data = sock.recv(256)
if not data:
sys.stdout.write('\r\n*** EOF ***\r\n\r\n')
sys.stdout.flush()
break
sys.stdout.write(data)
sys.stdout.flush()
writer = threading.Thread(target=writeall, args=(chan,))
writer.start()
try:
while True:
d = sys.stdin.read(1)
if not d:
break
chan.send(d)
except EOFError:
# user hit ^Z or F6
pass