看到网上有很多通过telnet实现远程登录的例子,就是找不到关于ssh远程登录的例子,ssh2的可能会有一些,但是目前开发项目遇到了比较底层的东西,这个需要通过ssh1连接的,于是就有了这个实例。
今天要给大家带来的就是 java通过ssh1/ssh2远程连接服务器的实例,实例用到了一个jar包,名称是mindterm,下载地址http://tech.cryptzone.com/mindterm/mindterm.html
废话不多说,看代码...
SshRequestHandler.java
package examples;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.SecureRandom;
import org.apache.log4j.Logger;
import com.mindbright.nio.NetworkConnection;
import com.mindbright.ssh.SSHConsoleClient;
import com.mindbright.ssh2.SSH2ConsoleRemote;
import com.mindbright.ssh2.SSH2SimpleClient;
import com.mindbright.ssh2.SSH2Transport;
import com.mindbright.util.RandomSeed;
import com.mindbright.util.SecureRandomAndPad;
public class SshRequestHandler {
public static final Logger logger = Logger.getLogger(SshRequestHandler.class);
//SSH1变量
public SSHConsoleClient client_ssh1=null;
//SSH2变量
public SSH2ConsoleRemote client_ssh2=null;
//通用变量
private String version=null;//SSH1/SSH2:1/2
public static boolean echo = false;
/
public boolean isEcho() {
return echo;
}
public void setEcho(boolean echo) {
SshRequestHandler.echo = echo;
}
public boolean login(String server, int port, String user, String password,String version){
try {
this.version=version;
if (version.equals("ssh1"))
{
SSH1_imp ssh_imp=new SSH1_imp(server, String.valueOf(port), user, password);
client_ssh1 = new SSHConsoleClient(ssh_imp.getSrvHost(), ssh_imp.getSrvPort(),ssh_imp,ssh_imp);
if(client_ssh1.shell())
{
echo=true;
logger.debug("ssh1登录成功");
return true;
}
else
{
echo=false;
return false;
}
}
else
{
SSH2Transport transport = new SSH2Transport(NetworkConnection.open(server, port),createSecureRandom());
SSH2SimpleClient Ssh2 = new SSH2SimpleClient(transport,user, password);
client_ssh2 = new SSH2ConsoleRemote(Ssh2.getConnection());
if(client_ssh2.shell())
{
echo=true;
logger.debug("SSH2登录成功");
return true;
}
else
{
echo=true;
return false;
}
}
} catch (Exception e) {
logger.error("登录失败:"+e.getMessage());
echo=false;
return false;
}
}
private SecureRandomAndPad createSecureRandom()
{
byte[] seed;
File devRandom = new File("/dev/urandom");
if (devRandom.exists()) {
RandomSeed rs = new RandomSeed("/dev/urandom", "/dev/urandom");
seed = rs.getBytesBlocking(20);
} else {
seed = RandomSeed.getSystemStateHash();
}
return new SecureRandomAndPad(new SecureRandom(seed));
}
public InputStream exeCommend(String cmd)
{
try
{
if(version.equals("ssh1"))
{
OutputStream os = client_ssh1.getStdIn();
os.write((cmd).getBytes());
os.flush();
Thread.sleep(2000);
return client_ssh1.getStdOut();
}
else
{
OutputStream os = client_ssh2.getStdIn();
os.write((cmd).getBytes());
os.flush();
Thread.sleep(1000);
return client_ssh2.getStdOut();
}
}
catch (Exception e)
{
logger.error(e.getMessage());
return null;
}
}
public static String getString(InputStream in) throws Exception
{
String returnString="";
while (true) {
int count = in.available();
if (count > 0) {
byte[] tmp = new byte[count];
in.read(tmp);
String temp=new String(tmp);
returnString+=temp;
}
if(returnString!=null&&returnString.length()>=0)
{
return returnString;
}
}
}
public static boolean getConnectioned()
{
return echo;
}
public void disconnect()
{
try {
if(version.equals("ssh1"))
{
client_ssh1.close();
echo=false;
}
else
{
client_ssh2.close();
echo=false;
}
logger.debug("断开SSH连接!");
} catch (Exception e) {
logger.error(e.getMessage());
}
}
}******************************************************************************************************************SSH1_imp.javapackage examples;
import java.io.File;
import java.io.IOException;
import java.security.interfaces.RSAPublicKey;
import java.util.Properties;
import com.mindbright.nio.NetworkConnection;
import com.mindbright.ssh.SSH;
import com.mindbright.ssh.SSHAuthenticator;
import com.mindbright.ssh.SSHClientUser;
import com.mindbright.ssh.SSHInteractor;
import com.mindbright.ssh.SSHInteractorAdapter;
import com.mindbright.ssh.SSHRSAKeyFile;
public class SSH1_imp extends SSHInteractorAdapter implements SSHAuthenticator, SSHClientUser{
private Properties props = new Properties();
SSH1_imp(String server,String port,String user,String password)
{
props.put("server", server);
props.put("port", port);
props.put("username", user);
props.put("password", password);
props.put("auth-method", "password");
}
public int getAliveInterval() {
return 0;
}
public int getCompressionLevel() {
return 0;
}
public int getConnectTimeout() {
return 60;
}
public String getDisplay() {
return null;
}
public int getHelloTimeout() {
return 60;
}
public SSHInteractor getInteractor() {
return this;
}
public int getKexTimeout() {
return 180;
}
public int getMaxPacketSz() {
return 0;
}
public NetworkConnection getProxyConnection() throws IOException {
return null;
}
public String getSrvHost() throws IOException {
return getProp("server");
}
private String getProp(String key) {
return (String)props.get(key);
}
public int getSrvPort() {
return Integer.parseInt(getProp("port"));
}
public boolean wantPTY() {
return false;
}
public boolean wantX11Forward() {
return false;
}
public int[] getAuthTypes(SSHClientUser arg0) {
return SSH.getAuthTypes(getProp("auth-method"));
}
public String getChallengeResponse(SSHClientUser arg0, String arg1)
throws IOException {
return null;
}
public int getCipher(SSHClientUser arg0) {
return SSH.CIPHER_3DES;
}
public SSHRSAKeyFile getIdentityFile(SSHClientUser arg0) throws IOException {
String idfile = System.getProperty("user.home") + File.separatorChar + ".ssh" + File.separatorChar + "identity";
return new SSHRSAKeyFile(idfile);
}
public String getIdentityPassword(SSHClientUser arg0) throws IOException {
return null;
}
public String getPassword(SSHClientUser arg0) throws IOException {
return getProp("password");
}
public String getUsername(SSHClientUser arg0) throws IOException {
return getProp("username");
}
public boolean verifyKnownHosts(RSAPublicKey arg0) throws IOException {
return true;
}
}****************************************************************************************************************************ConfigReadUtil.java
package examples;
import java.io.File;
import java.io.FileInputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Properties;
import org.apache.log4j.Logger;
/**
* 动态读取配置文件类
*
* @author liubing
*/
public class ConfigReadUtil {
private static Logger log = Logger.getLogger(ConfigReadUtil.class);
/**
* 属性文件全名
*/
private static final String PFILE = "config.properties";
/**
* 配置文件路径
*/
//private URI uri = null;
/**
* 属性文件所对应的属性对象变量
*/
private long m_lastModifiedTime = 0;
/**
* 对应于属性文件的文件对象变量
*/
private File m_file = null;
/**
* 属性文件所对应的属性对象变量
*/
private Properties m_props = null;
/**
* 唯一实例
*/
private static ConfigReadUtil m_instance = new ConfigReadUtil();
/**
* 私有构造函数
*
* @throws URISyntaxException
*/
private ConfigReadUtil() {
try {
m_lastModifiedTime = getFile().lastModified();
if (m_lastModifiedTime == 0) {
log.info(PFILE + "file does not exist!");
}
m_props = new Properties();
m_props.load(new FileInputStream(getFile()));
} catch (URISyntaxException e) {
System.err.println("文件路径不正确");
e.printStackTrace();
} catch (Exception e) {
System.err.println("文件读取异常");
e.printStackTrace();
}
}
/**
* 查找ClassPath路径获取文件
*
* @return File对象
* @throws URISyntaxException
*/
private File getFile() throws URISyntaxException {
URI fileUri = this.getClass().getClassLoader().getResource(PFILE)
.toURI();
m_file = new File(fileUri);
return m_file;
}
/**
* 静态工厂方法
*
* @return 返回ConfigurationRead的单一实例
*/
public synchronized static ConfigReadUtil getInstance() {
return m_instance;
}
/**
* 读取一特定的属性项
*/
public String getConfigItem(String name, String defaultVal) {
long newTime = m_file.lastModified();
// 检查属性文件是否被修改
if (newTime == 0) {
// 属性文件不存在
if (m_lastModifiedTime == 0) {
System.err.println(PFILE + " file does not exist!");
} else {
System.err.println(PFILE + " file was deleted!!");
}
return defaultVal;
} else if (newTime > m_lastModifiedTime) {
m_props.clear();
try {
m_props.load(new FileInputStream(getFile()));
} catch (Exception e) {
System.err.println("文件重新读取异常");
e.printStackTrace();
}
}
m_lastModifiedTime = newTime;
String val = m_props.getProperty(name);
if (val == null) {
return defaultVal;
} else {
return val;
}
}
/**
* 读取一特定的属性项
*
* @param name
* 属性项的项名
* @return 属性项的值(如此项存在), 空(如此项不存在)
*/
public String getConfigItem(String name) {
return getConfigItem(name, "");
}
}***********************************************************************************************************TestSsh.javapackage examples;
import org.apache.log4j.Logger;
public class TestSsh {
public static final Logger logger=Logger.getLogger(TestSsh.class);
private static String server;
private static int port;
private static String user;
private static String password;
private static String version ;// "SSH1"/"SSH2"
private static String cmdLine ;
public static void main(String[] args){
server="127.0.0.1";
port = 22;
user="administrator";
password="admin";
version="ssh2";
cmdLine="ls";
try {
SshRequestHandler ssh = new SshRequestHandler();
if(ssh.login(server, port, user, password, version))
{
logger.info(SshRequestHandler.getString(ssh.exeCommend(cmdLine+"\n")));
ssh.disconnect();
}
else
{
logger.debug("登录失败");
}
} catch (Exception e) {
logger.error("Exception:"+e);
}
}
}
-----------------------------------程序员 闫帆原创---------------------------------------
转载请注明原创人信息 程序员 闫帆yanfanvip