#!/usr/bin/env python

# Copyright (C) -  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 distributed 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.,
# Temple Place, Suite , Boston, MA - USA. import base64
from binascii import hexlify
import getpass
import os
import select
import socket
import sys
import time
import traceback
from paramiko.py3compat import input import paramiko
try:
import interactive
except ImportError:
from . import interactive def agent_auth(transport, username):
"""
Attempt to authenticate to the given transport using any of the private
keys available from an SSH agent.
""" agent = paramiko.Agent()
agent_keys = agent.get_keys()
if len(agent_keys) == :
return for key in agent_keys:
print('Trying ssh-agent key %s' % hexlify(key.get_fingerprint()))
try:
transport.auth_publickey(username, key)
print('... success!')
return
except paramiko.SSHException:
print('... nope.') def manual_auth(username, hostname):
default_auth = 'p'
auth = input('Auth by (p)assword, (r)sa key, or (d)ss key? [%s] ' % default_auth)
if len(auth) == :
auth = default_auth if auth == 'r':
default_path = os.path.join(os.environ['HOME'], '.ssh', 'id_rsa')
path = input('RSA key [%s]: ' % default_path)
if len(path) == :
path = default_path
try:
key = paramiko.RSAKey.from_private_key_file(path)
except paramiko.PasswordRequiredException:
password = getpass.getpass('RSA key password: ')
key = paramiko.RSAKey.from_private_key_file(path, password)
t.auth_publickey(username, key)
elif auth == 'd':
default_path = os.path.join(os.environ['HOME'], '.ssh', 'id_dsa')
path = input('DSS key [%s]: ' % default_path)
if len(path) == :
path = default_path
try:
key = paramiko.DSSKey.from_private_key_file(path)
except paramiko.PasswordRequiredException:
password = getpass.getpass('DSS key password: ')
key = paramiko.DSSKey.from_private_key_file(path, password)
t.auth_publickey(username, key)
else:
pw = getpass.getpass('Password for %s@%s: ' % (username, hostname))
t.auth_password(username, pw) # setup logging
paramiko.util.log_to_file('demo.log') username = ''
if len(sys.argv) > :
hostname = sys.argv[]
if hostname.find('@') >= :
username, hostname = hostname.split('@')
else:
hostname = input('Hostname: ')
if len(hostname) == :
print('*** Hostname required.')
sys.exit()
port =
if hostname.find(':') >= :
hostname, portstr = hostname.split(':')
port = int(portstr) # now connect
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((hostname, port))
except Exception as e:
print('*** Connect failed: ' + str(e))
traceback.print_exc()
sys.exit() try:
t = paramiko.Transport(sock)
try:
t.start_client()
except paramiko.SSHException:
print('*** SSH negotiation failed.')
sys.exit() try:
keys = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
except IOError:
try:
keys = paramiko.util.load_host_keys(os.path.expanduser('~/ssh/known_hosts'))
except IOError:
print('*** Unable to open host keys file')
keys = {} # check server's host key -- this is important.
key = t.get_remote_server_key()
if hostname not in keys:
print('*** WARNING: Unknown host key!')
elif key.get_name() not in keys[hostname]:
print('*** WARNING: Unknown host key!')
elif keys[hostname][key.get_name()] != key:
print('*** WARNING: Host key has changed!!!')
sys.exit()
else:
print('*** Host key OK.') # get username
if username == '':
default_username = getpass.getuser()
username = input('Username [%s]: ' % default_username)
if len(username) == :
username = default_username agent_auth(t, username)
if not t.is_authenticated():
manual_auth(username, hostname)
if not t.is_authenticated():
print('*** Authentication failed. :(')
t.close()
sys.exit() chan = t.open_session()
chan.get_pty()
chan.invoke_shell()
print('*** Here we go!\n')
interactive.interactive_shell(chan,username, hostname)
chan.close()
t.close() except Exception as e:
print('*** Caught exception: ' + str(e.__class__) + ': ' + str(e))
traceback.print_exc()
try:
t.close()
except:
pass
sys.exit()
# Copyright (C) -  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 distributed 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.,
# Temple Place, Suite , Boston, MA - USA. import socket
import sys
from paramiko.py3compat import u
import time # windows does not have termios...
try:
import termios
import tty
has_termios = True
except ImportError:
has_termios = False def interactive_shell(chan,username, hostname):
if has_termios:
posix_shell(chan,username, hostname)
else:
windows_shell(chan,username, hostname) def posix_shell(chan,username, hostname):
import select oldtty = termios.tcgetattr(sys.stdin)
try:
tty.setraw(sys.stdin.fileno())
tty.setcbreak(sys.stdin.fileno())
chan.settimeout(0.0)
ret_name = []
with open('history.log','ab+') as f:
while True:
r, w, e = select.select([chan, sys.stdin], [], [])
if chan in r:
try:
x = u(chan.recv())
if len(x) == :
sys.stdout.write('\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()
ret_name.append(x)
if x == '\r':
c_time = time.strftime('%Y-%m-%d %H:%M:%S')
cmd = ''.join(ret_name).replace('\r','\n')
log = '%s %s %s %s'%(hostname,username,c_time,cmd)
f.write(log)
               ret_name = [] if len(x) == :
break
chan.send(x) 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()
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()
if not d:
break
chan.send(d)
except EOFError:
# user hit ^Z or F6
pass

堡垒机 paramiko代码的更多相关文章

  1. 堡垒机--paramiko模块

    做堡垒机之前,来了解一下paramiko模块. 实际上底层封装的SSH. SSHclient(1) import paramiko #实例化一个ssh ssh = paramiko.SSHClient ...

  2. python之路 堡垒机paramiko

    paramiko 1.安装 pip3 install paramiko 二.使用 SSHClient 用于连接远程服务器并执行基本命令 基于用户名密码连接: import paramiko # 创建S ...

  3. 堡垒机 paramiko 自动登陆代码

    #!/usr/bin/env python # Copyright (C) - Robey Pointer <robeypointer@gmail.com> # # This file i ...

  4. 堡垒机paramiko模块

    paramiko简介: 模拟ssh客户端,使用ssh协议,基于sftp协议等做批量管理.例如处理用ssh登陆一千台机器执行同一个命令,或下载上传文件等需求 基于用户名密码登录执行命令: import ...

  5. paramiko 堡垒机

    用paramiko写堡垒机 paramiko paramiko模块,基于SSH用于连接远程服务器并执行相关操作. 基本用法 SSHClient 基于用户名密码连接: 基础用法: import para ...

  6. python远程连接paramiko 模块和堡垒机实现

    paramiko使用 paramiko模块是基于python实现了SSH2远程安全连接,支持认证和密钥方式,可以实现远程连接.命令执行.文件传输.中间SSH代理功能 安装 pip install pa ...

  7. 利用paramiko模块实现堡垒机+审计功能

    paramiko模块是一个远程连接服务器,全真模拟ssh2协议的python模块,借助paramiko源码包中的demos目录下:demo.py和interactive.py两个模块实现简单的堡垒机+ ...

  8. paramiko堡垒机、线程及锁

    1.使用paramiko实现ssh连接和scp拷贝 开发堡垒机之前,先来学习Python的paramiko模块,该模块机遇SSH用于连接远程服务器并执行相关操作 1.1 SSHClient 用于连接远 ...

  9. Python自动化运维之19、Paramiko模块和堡垒机实战

    paramiko模块 paramiko是一个用于做远程控制的模块,使用该模块可以对远程服务器进行命令或文件操作,值得一说的是,fabric和ansible内部的远程管理就是使用的paramiko来现实 ...

随机推荐

  1. 简单实现Redis缓存中的排序功能

    1.在实现缓存排序功能之前,必须先明白这一功能的合理性.不妨思考一下,既然可以在数据库中排序,为什么还要把排序功能放在缓存中实现呢?这里简单总结了两个原因:首先,排序会增加数据库的负载,难以支撑高并发 ...

  2. linux下创建和删除软、硬链接

    linux下创建和删除软.硬链接 在Linux系统中,内核为每一个新创建的文件分配一个Inode(索引结点),每个文件都有一个惟一的inode号.文件属性保存在索引结点里,在访问文件时,索引结点被复制 ...

  3. Tomcat安装、启动和配置

    Tomcat服务器介绍 Tomcat是一个免费开发源代码的web应用服务器,具有与IIS.Apache等web服务器一样处理html页面的功能,另外它还是一个Servlet和JSP容器,独立的serv ...

  4. mysql从只有一个备份文件(多个数据库的备份)中恢复数据到指定数据库

    mysql -uroot -p 要恢复的数据库的名字 --one-database<备份文件

  5. Apache查看并发及TIME_WAIT过多的解决

    1.查看并发#ps -ef | grep httpd -c2.查看并发数及tpc连接状态netstat -n | awk '/^tcp/ {++S[$NF]} END {for(a in S) pri ...

  6. he time that it takes to bring a block from disk into main memory

    DATABASE SYSTEM CONCEPTS, SIXTH EDITION There is a trade-off that the system designer must make betw ...

  7. SQL_NO_CACHE

    http://dev.mysql.com/doc/refman/5.7/en/query-cache-in-select.html MySQL 5.7 Reference Manual  /  ... ...

  8. Merge用法

    Merge用来从一个表中选择一些数据更新或者插入到另一个表中.而最终是用更新还是用插入的方式取决于该语句中的条件. 下面我们简单的举一个例子:   SQL> create table merge ...

  9. ie6 css sprites重复加载问题

    _html{zoom:expression(function(ele){ele.style.zoom = "1";document.execCommand("Backgr ...

  10. Java程序设计的基本原则

    Java程序设计的基本原则-1 1.面向对象 这是java编程里面大家公认的第一原则 2.优先使用对象组合而非类继承 3.分层 最典型的三层架构,表现层-->逻辑层-->数据层 表现层功能 ...