java SSH访问linux服务器 并执行命令

1 .引入com.jcraft.jsch jar

2.java代码 sshCommandUtil.java


import com.jcraft.jsch.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Vector;

public class SSHCommandUtil {
private String ipAddress;
private String username;
private String password;
public static final int DEFAULT_SSH_PORT = 22;
private Vector<String> stdout;


public SSHCommandUtil(final String ipAddress, final String username, final String password) {
this.ipAddress = ipAddress;
this.username = username;
this.password = password;
stdout = new Vector<String>();
}

public int execute(final String command) {
int returnCode = 0;
JSch jsch = new JSch();
MyUserInfo userInfo = new MyUserInfo();

try {
// Create and connect session.
Session session = jsch.getSession(username, ipAddress, DEFAULT_SSH_PORT);
session.setPassword(password);
session.setUserInfo(userInfo);
session.connect();

// Create and connect channel.
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);

channel.setInputStream(null);
BufferedReader input = new BufferedReader(new InputStreamReader(channel
.getInputStream()));

channel.connect();
System.out.println("The remote command is: " + command);

// Get the output of remote command.
String line;
while ((line = input.readLine()) != null) {
stdout.add(line);
}
input.close();

// Get the return code only after the channel is closed.
if (channel.isClosed()) {
returnCode = channel.getExitStatus();
}

// Disconnect the channel and session.
channel.disconnect();
session.disconnect();
} catch (JSchException e) {
System.out.println("链接不到服务器,请确认服务器状态");
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return returnCode;
}

public Vector<String> getStandardOutput() {
return stdout;
}


}

/**
* 根据服务ip,用户名,密码登录服务器并执行shell命令查看其内存和硬盘使用情况
* @param ip
* @param username
* @param pwd
* @return
*/
public static Vector<String> getMemAndDisk(String ip,String username,String pwd){
SSHCommandUtil sshCommandUtil = new SSHCommandUtil(ip, username, pwd);
sshCommandUtil.execute("free -g| sed -n '2p;2q'");//获取内存信息
sshCommandUtil.execute("df -h| sed -n '3p;3q'");//获取硬盘信息
Vector<String> stdout = sshCommandUtil.getStandardOutput();
return stdout;
}
}


3.java 代码 MyUserInfo.java

import com.jcraft.jsch.UserInfo;

/**
* Created by lill on 2015/11/12.
*/
public class MyUserInfo implements UserInfo {
private String password;

private String passphrase;

@Override
public String getPassphrase() {
System.out.println("MyUserInfo.getPassphrase()");
return null;
}

@Override
public String getPassword() {
System.out.println("MyUserInfo.getPassword()");
return null;
}

@Override
public boolean promptPassphrase(final String arg0) {
System.out.println("MyUserInfo.promptPassphrase()");
System.out.println(arg0);
return false;
}

@Override
public boolean promptPassword(final String arg0) {
System.out.println("MyUserInfo.promptPassword()");
System.out.println(arg0);
return false;
}

@Override
public boolean promptYesNo(final String arg0) {
System.out.println("MyUserInfo.promptYesNo()");
System.out.println(arg0);
if (arg0.contains("The authenticity of host")) {
return true;
}
return false;
}

@Override
public void showMessage(final String arg0) {
System.out.println("MyUserInfo.showMessage()");
}
}


4.java 测试方法
/**
* 测试方法
* @param args
*/
public static void main(final String [] args) {
SSHCommandUtil sshCommandUtil = new SSHCommandUtil(ip, username,password);
sshCommandUtil.execute("free -g| sed -n '2p;2q'");//获取内存信息
sshCommandUtil.execute("df -h| sed -n '3p;3q'");//获取硬盘信息
Vector<String> stdout=sshCommandUtil.getStandardOutput();
int i=0;
for (String str : stdout) {
if(i==0){
//memList= RegexOroUtil.getAllResult(str, "[0-9]\\d*\\.?\\d*");//java正则形式拆分
String tt[] = str.split("\\s{1,}");//按照空格分割字符串,多个空格作为一个空格对字符串进行分割 split形式
System.out.print(tt);
}else {

// diskList = RegexOroUtil.getAllResult(str, "[0-9]\\d*\\.?\\d*");//java正则形式拆分
String tt1[] = str.split("\\s{1,}");//按照空格分割字符串,多个空格作为一个空格对字符串进行分割 split形式
System.out.print(tt1);
}
i++;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值