ssh执行远程操作
命令格式
复制代码 代码如下:
ssh -p $port $user@$p 'cmd'
$port : ssh连接端口号
$user: ssh连接用户名
$ip:ssh连接的ip地址
cmd:远程服务器需要执行的操作
准备工作
基于公私钥认证或者用户名密码认证能确保登录到远程local2服务器(有点基本运维知识的人做这个事情都不是问题)
cmd如果是脚本,注意绝对路径问题(相对路径在远程执行时就是坑)
不足
这个命令可以满足我们大多数的需求,但是通常运维部署很多东西的时候需要root权限,但是有几处限制:
远程服务器local2禁止root用户登录
在远程服务器脚本里转换身份用expect需要send密码,这样不够安全
ssh的-t参数
复制代码 代码
-t Force pseudo-tty allocation. This can be used to execute arbitrary screen-based programs on a remote machine, which can be very useful, e.g. when implementing menu services. Multiple -t options force tty allocation, even if ssh has no local tty.
译一下:就是可以提供一个远程服务器的虚拟tty终端,加上这个参数我们就可以在远程服务器的虚拟终端上输入自己的提权密码了,非常安全
命令格式
复制代码 代码如下:
ssh -t -p $port $user@$ip 'cmd'
示例脚本
复制代码 代码如下:
#!/bin/bash
#变量定义
ip_array=("192.168.1.1" "192.168.1.2" "192.168.1.3")
user="test1"
remote_cmd="/home/test/1.sh"
#本地通过ssh执行远程服务器的脚本
for ip in ${ip_array[*]}
do
if [ $ip = "192.168.1.1" ]; then
port="7777"
else
port="22"
fi
ssh -t -p $port $user@$ip "remote_cmd"
done
这个方法还是很方便的,-t虚拟出一个远程服务器的终端,在多台服务器同时部署时确实节约了不少时间啊!
用java访问远程shell脚本代码如下:
package com.upsmart.util;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import org.springframework.stereotype.Component;
@Component
public class RemoteShellTool {
private Connection conn;
private String ipAddr;
private int port;
private String charset = Charset.defaultCharset().toString();
private String userName;
private String password;
public RemoteShellTool(String ipAddr, int port, String userName, String password,
String charset) {
this.ipAddr = ipAddr;
this.port = port;
this.userName = userName;
this.password = password;
if (charset != null) {
this.charset = charset;
}
}
public boolean login() throws IOException {
conn = new Connection(ipAddr, port);
conn.connect(); // 连接
return conn.authenticateWithPassword(userName, password); // 认证
}
public String exec(String cmds) {
InputStream in = null;
String result = "";
try {
if (this.login()) {
Session session = conn.openSession(); // 打开一个会话
session.execCommand(cmds);
in = session.getStdout();
result = this.processStdout(in, this.charset);
session.close();
conn.close();
}
} catch (IOException e1) {
e1.printStackTrace();
}
return result;
}
public String processStdout(InputStream in, String charset) {
byte[] buf = new byte[1024];
StringBuffer sb = new StringBuffer();
try {
while (in.read(buf) != -1) {
sb.append(new String(buf, charset));
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
/**
* @param args
*/
public static void main(String[] args) {
RemoteShellTool tool = new RemoteShellTool("192.168.55.135", 8130, "pengxiaohe",
"920125pxh", "utf-8");
String result = tool.exec("~/disk/start.sh");
System.out.print(result);
}
}