(1) 脚本命令的输入,和显示内容的输出
//创建连接,传入一个需要登陆的ip地址和port
Connection conn = new Connection(IP, SERVER_SSH_PORT);
//链接
conn.connect();
//账号,密码验证
boolean isAuthenticated = conn.authenticateWithPassword(admin, pwd1);
if (isAuthenticated == false) {
throw new IOException("密码不正确!");
}
打开一个session,有点象Hibernate的session ,执行你需要的linux 脚本命令 。
Session sess = conn.openSession();
方法一.直接使用封装好的执行命令
sess.execCommand("last");
方法二.使用脚本输入流输入:必须添加一下语句开启:
session.requestDumbPTY();
session.startShell();
即可获取输入输出流
InputStream in = sess.getStdout();
InputStream err = sess.getStderr();
OutputStream out = sess.getStdin()
使用下面语句直接吧字符串命令写入即可:
session.getStdin().write((cmd + "\n").getBytes());
(2) 下载和上传文件的字节流:
先创建SCPClient对象,用于上传和下载操作:
SCPClient client = new SCPClient(conn);
下载文件字节流:
private static byte[] getRemoteFileBytes(SCPClient client, String remoteFile) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
client.get(remoteFile, bos);
bos.flush();
byte[] bytes = bos.toByteArray();
bos.close();
return bytes;
}
上传文件字节流:
client.put(fileBytes, fileName, pathFile);
直接传输文件
//服务器端的文件下载到本地的目录下
scpClient.getFile("/home/oracle/RUNNING.txt", "C:/");
//将本地文件上传到服务器端的目录下
scp.putFile("C:/RUNNING.txt", "/home/oracle");
输入命令并显示结果的方法参考:
private static boolean sessionExcuteEnd = false;
private static long sessionLogOutTime = System.currentTimeMillis();
/**
* 执行命令
* @param session
* @param cmds
* @throws IOException
*/
public static void excuteCommands(Session session, String... cmds) throws IOException {
sessionExcuteEnd = false;
final InputStream is = new StreamGobbler(session.getStdout());
new Thread() {
public void run() {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while (true) {
try {
sessionLogOutTime = System.currentTimeMillis();
String line = br.readLine();
if (line == null) break;
System.out.println(line);
} catch (IOException e) {
e.printStackTrace();
}
}
try {
is.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("END");
sessionExcuteEnd = true;
}
}.start();
session.requestDumbPTY();
session.startShell();
for (String cmd : cmds) {
//2秒没日志响应,则输出下一步命令
while (System.currentTimeMillis() < sessionLogOutTime + 2000) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
sessionLogOutTime = System.currentTimeMillis();
session.getStdin().write((cmd + "\n").getBytes());
}
while (!sessionExcuteEnd) {
if (System.currentTimeMillis() - sessionLogOutTime > 5000) {//5秒未打印出日志,结束
session.close();
break;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
附加一个简单的实例运用:
public class Update {
private static int countSession = 0;
public static void main(String[] args) {
try {
// 更新文件准备
List configlist = Config.loadConfigs();
File updateFile = new File("./updatefiles/server.zip");
if (!updateFile.exists()) {
System.out.println("更新文件server.zip不存在");
return;
}
System.out.println(" 文件最后修改时间:" + new Timestamp(updateFile.lastModified()).toString());
/**
* 读取文件字节流
*/
final byte[] updateFileBytes = FileAndByteUtils.readFromFile(updateFile);
Scanner scan = new Scanner(System.in);
System.out.println("start ? (yes/no)");
if (!scan.nextLine().toLowerCase().equals("yes")) {
System.out.println("exit");
System.exit(0);
}
// 开始
for (final String[] configs : configlist) {
// configs[0]: id ;configs[1] : ip
// 开始连接
if (configs == null) {
return;
}
/**连接*/
final Connection conn = new Connection(configs[1], Config.PORT);
conn.connect();
/**账号验证*/
boolean isAuthenticated =
conn.authenticateWithPassword(Config.ADMIN,Config.PWD);
if (isAuthenticated == false) {
System.out.println("密码错误");
throw new IOException("Authentication failed.");
}
countSession++;
// 打开session
final Session session = conn.openSession();
// 上传文件
SCPClient client = new SCPClient(conn);
client.put(updateFileBytes, "xlsbz_server.zip", "/app/mhfx/");
System.out.println(configs[0] + "区服务器更新数据上传 完毕~~~~");
new Thread(new Runnable() {
public void run() {
try {
session.requestDumbPTY();
session.startShell();
OutputStream fout = session.getStdin();
// 输入命令
System.out.println(configs[0] + " :START");
fout.write(("bash xlsbz_server/bin/telnet.sh" + "\n").getBytes());
Thread.sleep(1000);
fout.write(("freeze" + "\n").getBytes());
Thread.sleep(60000);
fout.write(("quit" + "\n").getBytes());
Thread.sleep(60000);
// 完成关闭Session和连接
session.close();
Thread.sleep(1000);
conn.close();
Thread.sleep(1000);
countSession--;
System.out.println(configs[0] + " : END");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
final InputStream fin = session.getStdout();
new Thread(new Runnable() {
@Override
public void run() {
BufferedReader br = new BufferedReader(new InputStreamReader(fin));
String line = null;
try {
while ((line = br.readLine()) != null) {
System.out.println(configs[0] + ": " + line);
if (line.contains("quit")) {
continue;
}
if ((line.contains("command not found") && !line.startsWith("-bash: A:"))
|| line.contains("no cmd")) {
System.out.println("出错 command not found");
System.exit(0);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
while (true) {
if (countSession == 0) {
break;
}
System.out.println("正在运行中");
try {
Thread.sleep(30000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("finsh");
}
}
ch.ethz.ssh2的API: 相关API说明
下载地址: Ganymed SSH-2 for Java