JSch 通过公钥登录执行命令

import java.awt.Container;

import java.awt.GridBagConstraints;

import java.awt.GridBagLayout;

import java.awt.Insets;

 

import javax.swing.JFileChooser;

import javax.swing.JLabel;

import javax.swing.JOptionPane;

import javax.swing.JPanel;

import javax.swing.JPasswordField;

import javax.swing.JTextField;

 

import com.jcraft.jsch.Channel;

import com.jcraft.jsch.JSch;

import com.jcraft.jsch.Session;

import com.jcraft.jsch.UIKeyboardInteractive;

import com.jcraft.jsch.UserInfo;

 

public class Test {

public static void main(String[] arg) {

 

try {

JSch jsch = new JSch();

 

jsch.addIdentity("/" + System.getProperty("user.home") +"/.ssh/id_rsa");

String user = "root";

String host = "192.168.xx.xx";

 

Session session = jsch.getSession(user, host, 22);

 

// username and passphrase will be given via UserInfo interface.

UserInfo ui = new MyUserInfo();

session.setUserInfo(ui);

session.connect();

 

Channel channel = session.openChannel("shell");

 

channel.setInputStream(System.in);

channel.setOutputStream(System.out);

 

channel.connect();

} catch (Exception e) {

System.out.println(e);

}

}

 

public static class MyUserInfo implements UserInfo, UIKeyboardInteractive {

@Override

public String[] promptKeyboardInteractive(String destination, String name, String instruction, String[] prompt,

boolean[] echo) {

 

return null;

}

 

@Override

public String getPassphrase() {

// TODO Auto-generated method stub

return null;

}

 

@Override

public String getPassword() {

 

return null;

}

 

@Override

public boolean promptPassword(String message) {

// TODO Auto-generated method stub

return true;

}

 

@Override

public boolean promptPassphrase(String message) {

// TODO Auto-generated method stub

return true;

}

 

@Override

public boolean promptYesNo(String message) {

return true;

}

 

@Override

public void showMessage(String message) {

 

 

}

 

}

}

 

 

//jsch获取执行结果

package demo.ssh;

 

import java.io.BufferedReader;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.util.Vector;

 

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.util.StringUtils;

 

import com.jcraft.jsch.ChannelExec;

import com.jcraft.jsch.JSch;

import com.jcraft.jsch.Session;

import com.jcraft.jsch.UserInfo;

 

/**

 * @author mandy.hu

 *

 */

 

public class SSHCommandExecutor {

 

private static final Logger logger = LoggerFactory.getLogger(SSHCommandExecutor.class);

 

private String ipAddress;

 

private String username;

 

private String password;

 

public static final int DEFAULT_SSH_PORT = 22;

 

private static final String USERHOME = "/" + System.getProperty("user.home") + "/";

 

private static final String PRIVATEKEY = ".ssh/id_rsa";

 

private static final String PUBLICKEY = "/.ssh/id_rsa.pub";

 

private static final String DEFAULT_KNOWNHOSTS = "/.ssh/known_hosts";

 

private Vector<String> stdout;

 

public SSHCommandExecutor(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) throws Exception {

 

int returnCode = 0;

JSch jsch = new JSch();

SSHUserInfo userInfo = new SSHUserInfo();

 

// try {

if (logger.isInfoEnabled()) {

logger.info("ssh connect to server ip:{}, user:{}, password:{}", ipAddress, username, password);

}

// Create and connect session.

java.util.Properties config = new java.util.Properties();

config.put("StrictHostKeyChecking", "no");

Session session = null;

if ("test".equals("production")) {

logger.info("get session only by key:{}", ipAddress);

jsch.addIdentity(USERHOME + PRIVATEKEY);

session = jsch.getSession(username, ipAddress, 22);

UserInfo ui = new SSHUserInfo();

session.setUserInfo(ui);

} else {

if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {

logger.info("get session only by ip:{}", ipAddress);

jsch.setKnownHosts(USERHOME + DEFAULT_KNOWNHOSTS);

jsch.addIdentity(USERHOME + PRIVATEKEY);

session = jsch.getSession(ipAddress);

 

} else {

logger.info("get session by ip,username and password:{},{},{}", ipAddress, username, password);

session = jsch.getSession(username, ipAddress, DEFAULT_SSH_PORT);

session.setConfig(config);

session.setPassword(password);

session.setUserInfo(userInfo);

}

}

session.connect();

 

// Create and connect channel.

ChannelExec channel = (ChannelExec) session.openChannel("exec");

channel.setCommand(command);

channel.connect();

System.out.println(parse_String(channel.getInputStream()));

if (logger.isInfoEnabled()) {

logger.info("The remote command is: " + command);

}

 

// Disconnect the channel and session.

channel.disconnect();

session.disconnect();

return returnCode;

}

 

public String parse_String(InputStream in) throws Exception {

BufferedReader br = null;

 

br = new BufferedReader(new InputStreamReader(in));

String line = null;

StringBuilder sb = new StringBuilder();

while ((line = br.readLine()) != null) {

sb.append(line + "\n");

}

return sb.toString();

}

 

public static void main(String[] args) {

SSHCommandExecutor executor = new SSHCommandExecutor("192.168.xx.xx", "xxxx", "xxx");

try {

executor.execute("ls");

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值