#!/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. 【贴图】网友 snoopy 用《iHMI43 液晶模块》做的界面给大家看看

    请大家欣赏! iHMI43 4.3寸液晶模块购买地址: http://item.taobao.com/item.htm?id=20508376359

  2. Java发展史之Java由来

    Java:由Sun Microsystems公司于1995年5月推出的Java程序设计语言和Java平台的总称.Java语言是一种可以撰写跨平台应用软件的面向对象的程序设计语言,由当时任职太阳微系统的 ...

  3. velocity学习记录

    一.引入文件 静态引入:#include("./footer.vm.html") 动态引入:#parse("./header.vm.html") 说明:./为v ...

  4. 修改linux系统时间的方法(date命令)

    修改linux系统时间的方法(date命令) 来源:互联网 作者:佚名 时间:11-18 23:22:27 [大 中 小] date命令不仅可以显示系统当前时间,还可以用它来修改系统时间,下面简单的介 ...

  5. Ecshop、Discuz! 等开源产品的局限

    Ecshop.Discuz! 等开源产品的局限 记得今年年初,我初次接触Discuz!和Ecshop时,一阵阵地惊叹:成熟度这么高的产品,居然是免费的.我们这些搞传统软件开发的要怎么活?另外也奇怪,做 ...

  6. Alternative Representations for 4-Bit Integers

    COMPUTER ORGANIZATION AND ARCHITECTURE DESIGNING FOR PERFORMANCE NINTH EDITION

  7. Scripting Languages

    Computer Science An Overview _J. Glenn Brookshear _11th Edition A subset of the imperative programmi ...

  8. [dpdk] 读官方文档(2)

    续前节.切好继续: 一,文档里提到uio_pci_generic, igb_uio, vfio_pci三个内核模块,完全搞不懂,以及dpdk-devbind.py用来查看网卡状态,我得到了下边的输出: ...

  9. 防止sql注入,过滤敏感关键字

    //sql过滤关键字 public static bool CheckKeyWord(string sWord) { //过滤关键字 string StrKeyWord = @"select ...

  10. 答CsdnBlogger问-关于安卓入行和开发问题

    本文来自http://blog.csdn.net/liuxian13183/ ,引用必须注明出处! 问1:请问大牛对功能和框架的认识有哪些?(提问者:执笔记忆的空白) 比如对于一个小公司来说,什么样的 ...