如何利用Ganymed SSH-2模拟SSH操作
程序员文章站
2023-12-17 17:23:34
官方地址:
简介:ganymed ssh-2 for java is a library which implements the ssh-2 protocol in p...
官方地址:
简介:
ganymed ssh-2 for java is a library which implements the ssh-2 protocol in pure java (tested on j2se 1.4.2 and 5.0). it allows one to connect to ssh servers from within java programs. it supports ssh sessions (remote command execution and shell access), local and remote port forwarding, local stream forwarding, x11 forwarding, scp and sftp. there are no dependencies on any jce provider, as all crypto functionality is included.
程序:
复制代码 代码如下:
@test
public void testssh() {
string hostname = "192.168.0.1";
string username = "root";
string password = "password";
try {
/* create a connection instance */
connection conn = new connection(hostname);
/* now connect */
conn.connect();
system.out.println("connect ok");
/*
* authenticate. if you get an ioexception saying something like
* "authentication method password not supported by the server at this stage."
* then please check the faq.
*/
boolean isauthenticated = conn.authenticatewithpassword(username,password);
if (isauthenticated == false)
throw new ioexception("authentication failed.");
system.out.println("authentication ok");
/* create a session */
session sess = conn.opensession();
sess.execcommand("uname -a");
system.out.println("here is some information about the remote host:");
/*
* this basic example does not handle stderr, which is sometimes
* dangerous (please read the faq).
*/
inputstream stdout = new streamgobbler(sess.getstdout());
bufferedreader br = new bufferedreader(new inputstreamreader(stdout));
while (true) {
string line = br.readline();
if (line == null)
break;
system.out.println(line);
}
/* show exit status, if available (otherwise "null") */
system.out.println("exitcode: " + sess.getexitstatus());
/* close this session */
sess.close();
/* close the connection */
conn.close();
} catch (ioexception e) {
e.printstacktrace(system.err);
system.exit(2);
}
}
运行结果:
复制代码 代码如下:
connect ok
authentication ok
here is some information about the remote host:
linux localhost.localdomain 2.6.22 #1 smp wed aug 13 11:24:59 cst 2008 i686 i686 i386 gnu/linux
exitcode: 0