paramiko-客户端和服务器认证工具
required:
python+pycrypto
1.安装pycrypto
726 cd /opt/
727 wget http://ftp.dlitz.net/pub/dlitz/crypto/pycrypto/pycrypto-2.6.tar.gz
728 tar -zxvf pycrypto-2.6.tar.gz
729 cd pycrypto-2.6/
730 python
731 python setup.py build && python setup.py install
runtest:
>>> import Crypto
>>>
2.
pip install paramiko
error: command 'gcc' failed with exit status 1
yum install gcc libffi-devel python-devel openssl-devel
pip install paramiko
Installing collected packages: cffi, cryptography
Successfully installed cffi-1.6.0 cryptography-1.3.2
>>> import paramiko
>>>
import paramiko
import sys,os
host=sys.argv[1]
user='alex'
password=''
cmd=sys.argv[2] s=paramiko.SSHClient()
#加载本机的host密码文件
s.load_system_host_host_keys()
#Set policy to use when connecting to servers without a known host key
#第一次连接输入yes or no
s.set_missing_host_key_policy()
s.connect(host,22,user,password,timeout=5)
stdin.stdout,stders.exec_command(cmd)
cmd_result=stout.read(),stderr.read()
for line in cmd_result:
print line
s.close() #使用key连接远程
pkey_file=''
key=paramiko.RSAKey.from_private_key_file(pkey_file)
s.connect(host,port,username,pkey=key,timeout=5)
stdin,stout,stderr=s.exec_command(cmd)
s.close() #使用paramiko上传文件
hostnam='localhost'
user='alex'
password=''
s=paramiko.SSHClient()
s.load_system.host_keys()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
t=paramiko.Transport((host,22))
t.connect(username=user,password=password)
sftp=paramiko.SFTPClient.from_transport(t)
sftp.get('sourcefie','')
sftp.put('destfile','sourcefie')
s.close
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) == 0:
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) == 0:
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) == 0:
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) == 0:
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) > 1:
hostname = sys.argv[1]
if hostname.find('@') >= 0:
username, hostname = hostname.split('@')
else:
hostname = input('Hostname: ')
if len(hostname) == 0:
print('*** Hostname required.')
sys.exit(1)
port = 22
if hostname.find(':') >= 0:
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(1) try:
t = paramiko.Transport(sock)
try:
t.start_client()
except paramiko.SSHException:
print('*** SSH negotiation failed.')
sys.exit(1) 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(1)
else:
print('*** Host key OK.') # get username
if username == '':
default_username = getpass.getuser()
username = input('Username [%s]: ' % default_username)
if len(username) == 0:
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(1) chan = t.open_session()
chan.get_pty()
chan.invoke_shell()
print('*** Here we go!\n')
interactive.interactive_shell(chan)
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(1)
#/paramiko-master/demos/interactive.py
def posix_shell(chan):
import select
f=open('/tmp/log.log','a+') oldtty = termios.tcgetattr(sys.stdin)
try:
tty.setraw(sys.stdin.fileno())
tty.setcbreak(sys.stdin.fileno())
chan.settimeout(0.0) while True:
r, w, e = select.select([chan, sys.stdin], [], [])
if chan in r:
try:
x = u(chan.recv(1024))
if len(x) == 0:
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(1)
f.write(x)
f.flush()
if len(x) == 0:
break
chan.send(x) finally:
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
f.close()
paramiko-客户端和服务器认证工具的更多相关文章
- HttpClient三种不同的服务器认证客户端方案
http://blog.csdn.net/i_lovefish/article/details/9816783 HttpClient三种不同的认证方案: Basic, Digest and NTLM. ...
- 使用paramiko如何连接服务器?
本文和大家分享的是python开发中使用paramiko连接服务器的方法和步骤,希望通过本文的,对大家学习和使用paramiko有所帮助. ssh连接步骤 1.ssh server建立server p ...
- xmpp笔记2(客户端到服务器的例子)--xml
xmpp( 客户端到服务器的例子 ) 1 步:客户端初始流给服务器: <stream:stream xmlns='jabber:client' xmlns:stream='http://ethe ...
- [ActionScript 3.0] NetConnection建立客户端与服务器的双向连接
一个客户端与服务器之间的接口测试的工具 <?xml version="1.0" encoding="utf-8"?> <!--- - - - ...
- Oracle 客户端安装 + pl/sql工具安装配置
Oracle 客户端安装 + pl/sql工具安装配置 下载oracle客户端,并在本地安装. 11g下载地址为: http://www.oracle.com/technetwork/databas ...
- Windows下svn客户端和服务器的安装使用
svn,全称subversion, 是目前用的较多的开源的版本管理工具.相信有些经历的程序员应该都听说过它. 通常的svn服务器是搭建在Linux中,不过如果作为个人或者单个小组使用的话,就可以把sv ...
- 加密解密(2)*客户端,服务器,CA(Certificate Authority),公钥,私钥,证书,签名,验证
加密解密(2)*客户端,服务器,CA(Certificate Authority),公钥,私钥,证书,签名,验证 各角色比喻 客户端:通常为请求方,要验证服务器的身份. 服务器:通常为响应方,有时也要 ...
- api接口对于客户端的身份认证方式以及安全措施
转载 基于http协议的api接口对于客户端的身份认证方式以及安全措施 由于http是无状态的,所以正常情况下在浏览器浏览网页,服务器都是通过访问者的cookie(cookie中存储的jsession ...
- 利用Python中SocketServer 实现客户端与服务器间非阻塞通信
利用SocketServer模块来实现网络客户端与服务器并发连接非阻塞通信 版权声明 本文转自:http://blog.csdn.net/cnmilan/article/details/9664823 ...
随机推荐
- CSUFT 1005 Coffin Tiles
1005: Coffin Tiles Time Limit: 1 Sec Memory Limit: 128 MB Submit: 2 Solved: 2 Description ...
- STM32/GD32上内存堆栈溢出探测研究
无数次遭受堆栈溢出折磨,随着系统变得复杂,故障点越来越难以查找!主要溢出情况如下:1,一般RAM最后两块空间是堆Heap和栈Stack,堆从下往上用,栈从上往下用,任意一个用完,都会进入对方的空间2, ...
- bzoj 2818: Gcd GCD(a,b) = 素数
2818: Gcd Time Limit: 10 Sec Memory Limit: 256 MBSubmit: 1566 Solved: 691[Submit][Status] Descript ...
- UIEdgeInsetsMake, CGRectOffset等API参数详解
1, UIEdgeInsetsMake ( CGFloat top, CGFloat left, CGFloat bottom, CGFloat right ) 2,position点是相对suerL ...
- Cheatsheet: 2013 07.01 ~ 07.08
.NET The overhead of async/await in NET 4.5 await Task, Task.Wait and Friends 350 Interview Question ...
- VS2013自动注释插件
在程序编写的时候,你是否见过这种写法?整个项目每个cs文件头部都包含一个,版权,版本等信息的注释头? 类似这个类文件: /*************************************** ...
- Queue 应用——拓扑排序
1. 拓扑排序 题目描述:对一个有向无环图(Directed Acyclic Graph, DAG)G进行拓扑排序,是将G中所有顶点排成线性序列,是的图中任意一堆顶点u和v,若边(u, v)在E(G) ...
- Java EE 在网页输出九九乘法表、三角形、菱形
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding= ...
- C# 模拟鼠标写字
经常看到别人拿个四四方方的写字板用笔写字,用C#其实也可以实现,大致思路就是处理鼠标的坐标和Graphics, 代码如下: 首先声明两个全局变量 bool isMouseDown = false; P ...
- C# 获取打印机列表以及串口
C# 获取打印机列表以及默认打印机.串口列表. /// <summary> /// 获取本地已安装的打印机 /// </summary> /// <returns> ...