SSH编程的一些问题及解决方法(Granados&&SharpSSH)

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;

实现

[c-sharp] view plain copy
  1. class Reader : ISSHConnectionEventReceiver, ISSHChannelEventReceiver  
  2.     {  
  3.         public SSHConnection _conn;  
  4.         public bool _ready;  
  5.   
  6.         public void OnData(byte[] data, int offset, int length)  
  7.         {  
  8.             string sss = Encoding.ASCII.GetString(data, offset, length);  
  9.             MessageBox.Show(sss);  
  10.         }  
  11.         public void OnDebugMessage(bool always_display, byte[] data)  
  12.         {  
  13.             Debug.WriteLine("DEBUG: " + Encoding.ASCII.GetString(data));  
  14.         }  
  15.         public void OnIgnoreMessage(byte[] data)  
  16.         {  
  17.             Debug.WriteLine("Ignore: " + Encoding.ASCII.GetString(data));  
  18.         }  
  19.         public void OnAuthenticationPrompt(string[] msg)  
  20.         {  
  21.             Debug.WriteLine("Auth Prompt " + msg[0]);  
  22.         }  
  23.   
  24.         public void OnError(Exception error, string msg)  
  25.         {  
  26.             Debug.WriteLine("ERROR: " + msg);  
  27.         }  
  28.         public void OnChannelClosed()  
  29.         {  
  30.             Debug.WriteLine("Channel closed");  
  31.             _conn.Disconnect("");  
  32.             //_conn.AsyncReceive(this);  
  33.         }  
  34.         public void OnChannelEOF()  
  35.         {  
  36.             _pf.Close();  
  37.             Debug.WriteLine("Channel EOF");  
  38.         }  
  39.         public void OnExtendedData(int type, byte[] data)  
  40.         {  
  41.             Debug.WriteLine("EXTENDED DATA");  
  42.         }  
  43.         public void OnConnectionClosed()  
  44.         {  
  45.             Debug.WriteLine("Connection closed");  
  46.         }  
  47.         public void OnUnknownMessage(byte type, byte[] data)  
  48.         {  
  49.             Debug.WriteLine("Unknown Message " + type);  
  50.         }  
  51.         public void OnChannelReady()  
  52.         {  
  53.             _ready = true;  
  54.         }  
  55.         public void OnChannelError(Exception error, string msg)  
  56.         {  
  57.             Debug.WriteLine("Channel ERROR: " + msg);  
  58.         }  
  59.         public void OnMiscPacket(byte type, byte[] data, int offset, int length)  
  60.         {  
  61.         }  
  62.   
  63.         public PortForwardingCheckResult CheckPortForwardingRequest(string host, int port, string originator_host, int originator_port)  
  64.         {  
  65.             PortForwardingCheckResult r = new PortForwardingCheckResult();  
  66.             r.allowed = true;  
  67.             r.channel = this;  
  68.             return r;  
  69.         }  
  70.         public void EstablishPortforwarding(ISSHChannelEventReceiver rec, SSHChannel channel)  
  71.         {  
  72.             _pf = channel;  
  73.         }  
  74.   
  75.         public SSHChannel _pf;  
  76.     }  

调用方法如下:

[c-sharp] view plain copy
  1. public void conn2(string ip, string root, string pass,string cmd)  
  2.        {  
  3.            SSHConnectionParameter f = new SSHConnectionParameter();  
  4.            f.UserName = root;  
  5.            f.Password = pass;  
  6.            f.Protocol = SSHProtocol.SSH2;  
  7.            f.AuthenticationType = AuthenticationType.Password;  
  8.            f.WindowSize = 0x1000;  
  9.            Reader reader = new Reader();  
  10.            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);  
  11.            s.Connect(new IPEndPoint(IPAddress.Parse(ip), 22));  
  12.            _conn = SSHConnection.Connect(f, reader, s);  
  13.            reader._conn = _conn;  
  14.            SSHChannel ch = _conn.OpenShell(reader);  
  15.            reader._pf = ch;  
  16.            SSHConnectionInfo ci = _conn.ConnectionInfo;  
  17.   
  18.            Thread.Sleep(1000);  
  19.              
  20.            byte[] data = (new UnicodeEncoding()).GetBytes(cmd);  
  21.            reader._pf.Transmit(data);  
  22.        }  

 执行一般命令没问题,执行top命令会返回很多无法识别的字符,不知道是什么原因造成的。刚开始想写在web里的,但是,不等ondata()数据接收完毕连接就会断开,就费了点事情在winform中实现,

3、Sharpssh的实现

 

[c-sharp] view plain copy
  1. public string ssh_conn(string ip, string root, string pass, string command)  
  2.      {  
  3.          
  4.           SshStream ssh = new SshStream(ip, root, pass);  
  5.           ssh.Prompt = "#";  
  6.           ssh.RemoveTerminalEmulationCharacters = true;  
  7.           //Writing to the SSH channel  
  8.           string response = ssh.ReadResponse();  
  9.           ssh.Write(command);  
  10.           ssh.Flush();  
  11.           ssh.Write("/n");  
  12.           //Reading from the SSH channel  
  13.            response = ssh.ReadResponse();  
  14.            MessageBox.Show(response);  
  15.           return response;  
  16.           
  17.      }  

注意,一定要写上这句  ssh.Write("/n");而且要单独写,不要加在command里面,不然他遇到“#”就不会继续往下面显示了,这个执行任何命令都不会显示乱码。可以在http://sourceforge.net/projects/sharpssh上头下载,包括利用sfp传送文件,实现起来十分方便,


转自http://blog.csdn.net/qwldcl/article/details/4034803

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值