依赖的jar包
<dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.53</version> </dependency>
/** * java远程调用linux系统 */ def javaScpLinux(): Unit ={ val jsch = new JSch(); // 创建JSch对象 val host = "172.xx.xx.xx"; val port = 22; val user = "root"; val password = "root"; val command = "cd /opt;ls;";//执行多条指令使用";"隔开 val session = jsch.getSession(user, host, port); // 根据用户名,主机ip,端口获取一个Session对象 session.setPassword(password); // 设置密码 val config = new Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); // 为Session对象设置properties val timeout = 60000000; session.setTimeout(timeout); // 设置timeout时间 session.connect(); // 通过Session建立链接 val channelExec = session.openChannel("exec").asInstanceOf[ChannelExec]; channelExec.setCommand(command); channelExec.setErrStream(System.err); val in = channelExec.getInputStream(); channelExec.connect(); val out = IOUtils.toString(in, "UTF-8"); println(out) channelExec.disconnect(); session.disconnect(); }
/** * 使用ssh传文件 */ def sshupload(): Unit = { val hostname = "172.xx.xx.xx"; val port = 22; val username = "root"; val password = "root"; val jsch = new JSch(); jsch.getSession(username, hostname, port); val sshSession = jsch.getSession(username, hostname, port); sshSession.setPassword(password); val sshConfig = new Properties(); sshConfig.put("StrictHostKeyChecking", "no"); sshSession.setConfig(sshConfig); sshSession.connect(); val channel = sshSession.openChannel("sftp"); channel.connect(); val sftp = channel.asInstanceOf[ChannelSftp]; val dir = "/opt" val imagefile = new File("F:\\project\\1.jpg"); val imagefileFileName = "苹果.jpg"; //sftp.cd("/flume_tmp") val path="/flume_tmp/"+imagefileFileName val input = new FileInputStream(imagefile); sftp.put(input,path) sftp.disconnect() sshSession.disconnect() }