Java中通过jsch来连接远程服务器执行linux命令
2016-03-04 10:51
796 查看
有时候你可能需要通过代码来控制执行linux命令实现某些功能。
针对这类问题可以使用JSCH来实现,具体代码如下:
针对这类问题可以使用JSCH来实现,具体代码如下:
[code]public class CogradientImgFileManager{ private static final Logger log = LoggerFactory.getLogger(CogradientImgFileManager.class); private static ChannelExec channelExec; private static Session session = null; private static int timeout = 60000; // 测试代码 public static void main(String[] args){ try{ versouSshUtil("10.8.12.189","jmuser","root1234",22); runCmd("java -version","UTF-8"); }catch (Exception e){ // TODO Auto-generated catch block e.printStackTrace(); } } /** * 连接远程服务器 * @param host ip地址 * @param userName 登录名 * @param password 密码 * @param port 端口 * @throws Exception */ public static void versouSshUtil(String host,String userName,String password,int port) throws Exception{ log.info("尝试连接到....host:" + host + ",username:" + userName + ",password:" + password + ",port:" + port); JSch jsch = new JSch(); // 创建JSch对象 session = jsch.getSession(userName, host, port); // 根据用户名,主机ip,端口获取一个Session对象 session.setPassword(password); // 设置密码 Properties config = new Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); // 为Session对象设置properties session.setTimeout(timeout); // 设置timeout时间 session.connect(); // 通过Session建立链接 } /** * 在远程服务器上执行命令 * @param cmd 要执行的命令字符串 * @param charset 编码 * @throws Exception */ public static void runCmd(String cmd,String charset) throws Exception{ channelExec = (ChannelExec) session.openChannel("exec"); channelExec.setCommand(cmd); channelExec.setInputStream(null); channelExec.setErrStream(System.err); channelExec.connect(); InputStream in = channelExec.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in, Charset.forName(charset))); String buf = null; while ((buf = reader.readLine()) != null){ System.out.println(buf); } reader.close(); channelExec.disconnect(); } }
相关文章推荐
- linux深入分析进程调度
- Linux 常用命令
- Linux wget安装详解
- linux 下定时器timer的使用
- 解决linux挂载U盘时:Not authorized to perform operation
- centos6升级 python到2.7
- opencv 学习笔记(一)Archlinux+opencv+codeblocks
- Linux命令: ln
- Linux CTRL+ALT+DELETE
- Linux-ubuntu指令使用积累(长期更新)
- linux根据进程号PID查找启动程序的全路径
- CentOS_6.5配置iptables防火墙策略
- centOS防火墙iptables的设置教程
- Linux的使用
- 基于nrpe监控linux
- 开发必会的 Linux 命令
- 关于centos更新后virtualbox无法使用的问题
- Linux下批量Kill多个进程的方法
- Linux下批量Kill多个进程的方法
- 20 个 Linux 命令面试问答