SSH编程的一些问题及解决方法(Granados&&SharpSSH)
2009-03-29 22:34
507 查看
1、首先是OPENSSH的无法登陆显示(Granados和Sharpssh都有这个问题)“failed authentication”
打开sshd_config,按照如下的配置修改:
# This is the sshd server system-wide configuration file. See
# sshd_config(5) for more information.
# This sshd was compiled with PATH=/usr/bin:/bin:/usr/sbin:/sbin
# The strategy used for options in the default sshd_config shipped with
# OpenSSH is to specify options with their default value where
# possible, but leave them commented. Uncommented options change a
# default value.
#Port 22
#Protocol 2,1
#ListenAddress 0.0.0.0
#ListenAddress ::
# HostKey for protocol version 1
#HostKey /etc/ssh/ssh_host_key
# HostKeys for protocol version 2
#HostKey /etc/ssh/ssh_host_rsa_key
#HostKey /etc/ssh/ssh_host_dsa_key
# Lifetime and size of ephemeral version 1 server key
#KeyRegenerationInterval 1h
#ServerKeyBits 768
# Logging
#obsoletes QuietMode and FascistLogging
#SyslogFacility AUTH
#LogLevel INFO
# Authentication:
#LoginGraceTime 2m
#PermitRootLogin yes
#StrictModes yes
RSAAuthentication yes
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
# For this to work you will also need host keys in /etc/ssh/ssh_known_hosts
#RhostsRSAAuthentication no
# similar for protocol version 2
#HostbasedAuthentication no
# Change to yes if you don't trust ~/.ssh/known_hosts for
# RhostsRSAAuthentication and HostbasedAuthentication
#IgnoreUserKnownHosts no
# Don't read the user's ~/.rhosts and ~/.shosts files
#IgnoreRhosts yes
# To disable tunneled clear text passwords, change to no here!
PasswordAuthentication yes
#PermitEmptyPasswords no
# Change to no to disable s/key passwords
#ChallengeResponseAuthentication yes
# Kerberos options
#KerberosAuthentication no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes
#KerberosGetAFSToken no
# GSSAPI options
#GSSAPIAuthentication no
#GSSAPICleanupCredentials yes
# Set this to 'yes' to enable support for the deprecated 'gssapi' authentication
# mechanism to OpenSSH 3.8p1. The newer 'gssapi-with-mic' mechanism is included
# in this release. The use of 'gssapi' is deprecated due to the presence of
# potential man-in-the-middle attacks, which 'gssapi-with-mic' is not susceptible to.
#GSSAPIEnableMITMAttack no
# Set this to 'yes' to enable PAM authentication (via challenge-response)
# and session processing. Depending on your PAM configuration, this may
# bypass the setting of 'PasswordAuthentication' and 'PermitEmptyPasswords'
UsePAM yes
#AllowTcpForwarding yes
#GatewayPorts no
X11Forwarding yes
#X11DisplayOffset 10
#X11UseLocalhost yes
#PrintMotd yes
#PrintLastLog yes
#TCPKeepAlive yes
#UseLogin no
#UsePrivilegeSeparation yes
#PermitUserEnvironment no
#Compression yes
#ClientAliveInterval 0
#ClientAliveCountMax 3
#UseDNS yes
#PidFile /var/run/sshd.pid
#MaxStartups 10
# no default banner path
#Banner /some/path
# override default of no subsystems
Subsystem sftp /usr/lib/ssh/sftp-server
ssh_config file settings
# $OpenBSD: ssh_config,v 1.19 2003/08/13 08:46:31 markus Exp $
# This is the ssh client system-wide configuration file. See
# ssh_config(5) for more information. This file provides defaults for
# users, and the values can be changed in per-user configuration files
# or on the command line.
# Configuration data is parsed as follows:
# 1. command line options
# 2. user-specific file
# 3. system-wide file
# Any configuration value is only changed the first time it is set.
# Thus, host-specific definitions should be at the beginning of the
# configuration file, and defaults at the end.
# Site-wide defaults for various options
Host *
# ForwardAgent no
# ForwardX11 no
# If you do not trust your remote host (or its administrator), you
# should not forward X11 connections to your local X11-display for
# security reasons: Someone stealing the authentification data on the
# remote side (the "spoofed" X-server by the remote sshd) can read your
# keystrokes as you type, just like any other X11 client could do.
# Set this to "no" here for global effect or in your own ~/.ssh/config
# file if you want to have the remote X11 authentification data to
# expire after two minutes after remote login.
ForwardX11Trusted yes
# RhostsRSAAuthentication no
RSAAuthentication yes
PasswordAuthentication yes
# HostbasedAuthentication no
# BatchMode no
# CheckHostIP yes
# AddressFamily any
# ConnectTimeout 0
# StrictHostKeyChecking ask
# IdentityFile ~/.ssh/identity
# IdentityFile ~/.ssh/id_rsa
# IdentityFile ~/.ssh/id_dsa
# Port 22
# Protocol 2,1
# Cipher 3des
# Ciphers aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour,aes192-cbc,aes256-cbc
# EscapeChar ~
# GSSAPIAuthentication no
# GSSAPIDelegateCredentials no
# Set this to 'yes' to enable support for the deprecated 'gssapi' authentication
# mechanism to OpenSSH 3.8p1. The newer 'gssapi-with-mic' mechanism is included
# in this release. The use of 'gssapi' is deprecated due to the presence of
# potential man-in-the-middle attacks, which 'gssapi-with-mic' is not susceptible to.
# GSSAPIEnableMITMAttack no
注意红色部分,重启SSH,即可登陆,原因如下:
ChallengeResponseAuthentication
option set in the sshd_config configuration file. This is basically
turning-on keyboard-interactive authentication mode. There are 2
options available:
1. Set ChallengeResponseAuthentication no
2. Starting from SSIS+ 1.3 SR2 there is included support for keyboard-
interactive mode.
2、Granados的登陆编写,首先下载源码地址:http://www.routrek.co.jp/support/download/varaterm/granados200.tar.gz,一个小日本写的开源的东东,工程中添加Routrek.granados.dll(下载的包里有)的引用。添加Reader类,实现ISSHConnectionEventReceiver和ISSHChannelEventReceiver接口。首先引用命名空间:
using System.Threading;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using Routrek.Crypto;
using Routrek.SSHC;
using Routrek.SSHCV1;
using Routrek.SSHCV2;
using Routrek.Toolkit;
using Routrek.PKI;
实现
调用方法如下:
执行一般命令没问题,执行top命令会返回很多无法识别的字符,不知道是什么原因造成的。刚开始想写在web里的,但是,不等ondata()数据接收完毕连接就会断开,就费了点事情在winform中实现,
3、Sharpssh的实现
注意,一定要写上这句 ssh.Write("/n");而且要单独写,不要加在command里面,不然他遇到“#”就不会继续往下面显示了,这个执行任何命令都不会显示乱码。可以在http://sourceforge.net/projects/sharpssh上头下载,包括利用sfp传送文件,实现起来十分方便,
打开sshd_config,按照如下的配置修改:
# This is the sshd server system-wide configuration file. See
# sshd_config(5) for more information.
# This sshd was compiled with PATH=/usr/bin:/bin:/usr/sbin:/sbin
# The strategy used for options in the default sshd_config shipped with
# OpenSSH is to specify options with their default value where
# possible, but leave them commented. Uncommented options change a
# default value.
#Port 22
#Protocol 2,1
#ListenAddress 0.0.0.0
#ListenAddress ::
# HostKey for protocol version 1
#HostKey /etc/ssh/ssh_host_key
# HostKeys for protocol version 2
#HostKey /etc/ssh/ssh_host_rsa_key
#HostKey /etc/ssh/ssh_host_dsa_key
# Lifetime and size of ephemeral version 1 server key
#KeyRegenerationInterval 1h
#ServerKeyBits 768
# Logging
#obsoletes QuietMode and FascistLogging
#SyslogFacility AUTH
#LogLevel INFO
# Authentication:
#LoginGraceTime 2m
#PermitRootLogin yes
#StrictModes yes
RSAAuthentication yes
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
# For this to work you will also need host keys in /etc/ssh/ssh_known_hosts
#RhostsRSAAuthentication no
# similar for protocol version 2
#HostbasedAuthentication no
# Change to yes if you don't trust ~/.ssh/known_hosts for
# RhostsRSAAuthentication and HostbasedAuthentication
#IgnoreUserKnownHosts no
# Don't read the user's ~/.rhosts and ~/.shosts files
#IgnoreRhosts yes
# To disable tunneled clear text passwords, change to no here!
PasswordAuthentication yes
#PermitEmptyPasswords no
# Change to no to disable s/key passwords
#ChallengeResponseAuthentication yes
# Kerberos options
#KerberosAuthentication no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes
#KerberosGetAFSToken no
# GSSAPI options
#GSSAPIAuthentication no
#GSSAPICleanupCredentials yes
# Set this to 'yes' to enable support for the deprecated 'gssapi' authentication
# mechanism to OpenSSH 3.8p1. The newer 'gssapi-with-mic' mechanism is included
# in this release. The use of 'gssapi' is deprecated due to the presence of
# potential man-in-the-middle attacks, which 'gssapi-with-mic' is not susceptible to.
#GSSAPIEnableMITMAttack no
# Set this to 'yes' to enable PAM authentication (via challenge-response)
# and session processing. Depending on your PAM configuration, this may
# bypass the setting of 'PasswordAuthentication' and 'PermitEmptyPasswords'
UsePAM yes
#AllowTcpForwarding yes
#GatewayPorts no
X11Forwarding yes
#X11DisplayOffset 10
#X11UseLocalhost yes
#PrintMotd yes
#PrintLastLog yes
#TCPKeepAlive yes
#UseLogin no
#UsePrivilegeSeparation yes
#PermitUserEnvironment no
#Compression yes
#ClientAliveInterval 0
#ClientAliveCountMax 3
#UseDNS yes
#PidFile /var/run/sshd.pid
#MaxStartups 10
# no default banner path
#Banner /some/path
# override default of no subsystems
Subsystem sftp /usr/lib/ssh/sftp-server
ssh_config file settings
# $OpenBSD: ssh_config,v 1.19 2003/08/13 08:46:31 markus Exp $
# This is the ssh client system-wide configuration file. See
# ssh_config(5) for more information. This file provides defaults for
# users, and the values can be changed in per-user configuration files
# or on the command line.
# Configuration data is parsed as follows:
# 1. command line options
# 2. user-specific file
# 3. system-wide file
# Any configuration value is only changed the first time it is set.
# Thus, host-specific definitions should be at the beginning of the
# configuration file, and defaults at the end.
# Site-wide defaults for various options
Host *
# ForwardAgent no
# ForwardX11 no
# If you do not trust your remote host (or its administrator), you
# should not forward X11 connections to your local X11-display for
# security reasons: Someone stealing the authentification data on the
# remote side (the "spoofed" X-server by the remote sshd) can read your
# keystrokes as you type, just like any other X11 client could do.
# Set this to "no" here for global effect or in your own ~/.ssh/config
# file if you want to have the remote X11 authentification data to
# expire after two minutes after remote login.
ForwardX11Trusted yes
# RhostsRSAAuthentication no
RSAAuthentication yes
PasswordAuthentication yes
# HostbasedAuthentication no
# BatchMode no
# CheckHostIP yes
# AddressFamily any
# ConnectTimeout 0
# StrictHostKeyChecking ask
# IdentityFile ~/.ssh/identity
# IdentityFile ~/.ssh/id_rsa
# IdentityFile ~/.ssh/id_dsa
# Port 22
# Protocol 2,1
# Cipher 3des
# Ciphers aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour,aes192-cbc,aes256-cbc
# EscapeChar ~
# GSSAPIAuthentication no
# GSSAPIDelegateCredentials no
# Set this to 'yes' to enable support for the deprecated 'gssapi' authentication
# mechanism to OpenSSH 3.8p1. The newer 'gssapi-with-mic' mechanism is included
# in this release. The use of 'gssapi' is deprecated due to the presence of
# potential man-in-the-middle attacks, which 'gssapi-with-mic' is not susceptible to.
# GSSAPIEnableMITMAttack no
注意红色部分,重启SSH,即可登陆,原因如下:
ChallengeResponseAuthentication
option set in the sshd_config configuration file. This is basically
turning-on keyboard-interactive authentication mode. There are 2
options available:
1. Set ChallengeResponseAuthentication no
2. Starting from SSIS+ 1.3 SR2 there is included support for keyboard-
interactive mode.
2、Granados的登陆编写,首先下载源码地址:http://www.routrek.co.jp/support/download/varaterm/granados200.tar.gz,一个小日本写的开源的东东,工程中添加Routrek.granados.dll(下载的包里有)的引用。添加Reader类,实现ISSHConnectionEventReceiver和ISSHChannelEventReceiver接口。首先引用命名空间:
using System.Threading;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using Routrek.Crypto;
using Routrek.SSHC;
using Routrek.SSHCV1;
using Routrek.SSHCV2;
using Routrek.Toolkit;
using Routrek.PKI;
实现
class Reader : ISSHConnectionEventReceiver, ISSHChannelEventReceiver { public SSHConnection _conn; public bool _ready; public void OnData(byte[] data, int offset, int length) { string sss = Encoding.ASCII.GetString(data, offset, length); MessageBox.Show(sss); } public void OnDebugMessage(bool always_display, byte[] data) { Debug.WriteLine("DEBUG: " + Encoding.ASCII.GetString(data)); } public void OnIgnoreMessage(byte[] data) { Debug.WriteLine("Ignore: " + Encoding.ASCII.GetString(data)); } public void OnAuthenticationPrompt(string[] msg) { Debug.WriteLine("Auth Prompt " + msg[0]); } public void OnError(Exception error, string msg) { Debug.WriteLine("ERROR: " + msg); } public void OnChannelClosed() { Debug.WriteLine("Channel closed"); _conn.Disconnect(""); //_conn.AsyncReceive(this); } public void OnChannelEOF() { _pf.Close(); Debug.WriteLine("Channel EOF"); } public void OnExtendedData(int type, byte[] data) { Debug.WriteLine("EXTENDED DATA"); } public void OnConnectionClosed() { Debug.WriteLine("Connection closed"); } public void OnUnknownMessage(byte type, byte[] data) { Debug.WriteLine("Unknown Message " + type); } public void OnChannelReady() { _ready = true; } public void OnChannelError(Exception error, string msg) { Debug.WriteLine("Channel ERROR: " + msg); } public void OnMiscPacket(byte type, byte[] data, int offset, int length) { } public PortForwardingCheckResult CheckPortForwardingRequest(string host, int port, string originator_host, int originator_port) { PortForwardingCheckResult r = new PortForwardingCheckResult(); r.allowed = true; r.channel = this; return r; } public void EstablishPortforwarding(ISSHChannelEventReceiver rec, SSHChannel channel) { _pf = channel; } public SSHChannel _pf; }
调用方法如下:
public void conn2(string ip, string root, string pass,string cmd) { SSHConnectionParameter f = new SSHConnectionParameter(); f.UserName = root; f.Password = pass; f.Protocol = SSHProtocol.SSH2; f.AuthenticationType = AuthenticationType.Password; f.WindowSize = 0x1000; Reader reader = new Reader(); Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); s.Connect(new IPEndPoint(IPAddress.Parse(ip), 22)); _conn = SSHConnection.Connect(f, reader, s); reader._conn = _conn; SSHChannel ch = _conn.OpenShell(reader); reader._pf = ch; SSHConnectionInfo ci = _conn.ConnectionInfo; Thread.Sleep(1000); byte[] data = (new UnicodeEncoding()).GetBytes(cmd); reader._pf.Transmit(data); }
执行一般命令没问题,执行top命令会返回很多无法识别的字符,不知道是什么原因造成的。刚开始想写在web里的,但是,不等ondata()数据接收完毕连接就会断开,就费了点事情在winform中实现,
3、Sharpssh的实现
public string ssh_conn(string ip, string root, string pass, string command) { SshStream ssh = new SshStream(ip, root, pass); ssh.Prompt = "#"; ssh.RemoveTerminalEmulationCharacters = true; //Writing to the SSH channel string response = ssh.ReadResponse(); ssh.Write(command); ssh.Flush(); ssh.Write("/n"); //Reading from the SSH channel response = ssh.ReadResponse(); MessageBox.Show(response); return response; }
注意,一定要写上这句 ssh.Write("/n");而且要单独写,不要加在command里面,不然他遇到“#”就不会继续往下面显示了,这个执行任何命令都不会显示乱码。可以在http://sourceforge.net/projects/sharpssh上头下载,包括利用sfp传送文件,实现起来十分方便,
相关文章推荐
- SSH编程的一些问题及解决方法(Granados&&SharpSSH)
- ssh 'diffie-hellman-group1-sha1' 问题解决方法
- 如何尽可能高效地使用论坛+解决编程问题的一些方法
- 编程一些问题及其解决方法
- 使用ssh或者远程执行命令是的一些问题解决方法
- Failed to read schema document 'http://code.alibabatech.com/schema/dubbo/dubbo.xsd'问题解决方法
- impdp的一些实际问题解决方法
- Uboot的移植中遇到的一些问题,及解决方法。
- 开发中所遇到的一些问题与解决方法(2)
- C#中??和?分别是什么意思? 在ASP.NET开发中一些单词的标准缩写 C#SESSION丢失问题的解决办法 在C#中INTERFACE与ABSTRACT CLASS的区别 SQL命令语句小技巧 JQUERY判断CHECKBOX是否选中三种方法 JS中!=、==、!==、===的用法和区别 在对象比较中,对象相等和对象一致分别指的是什么?
- 解决方法:SQL2008 链接服务器 访问接口 "SQLNCLI10" 的架构行集 出错的问题!
- 在决定使用ClickOnce发布你的软件前,应该知道的一些事情(一些常见问题解决方法)
- fedora6的安装及一些可能遇到问题的解决方法
- linux下mysql error #1036 - Table 'xxxx' is read only问题的解决方法
- MFC一些问题的解决方法
- kxml2在Eclipse和NetBeans中的一些问题的解决方法
- ubuntu上网速度慢问题以及一些解决方法
- VC6.0 工程转到VS2008一些问题的描述及解决方法(附有VS2008发布程序介绍)
- C#遇到的一些问题与解决方法
- Linux 编译报错 -- undefined reference to 问题解决方法 (具体'pthread_create'和opencv看文章最后两条)