首页 > 解决方案 > 在 SSH Sampler JMeter 中切换到 root 用户

问题描述

我正在使用 JMeter SSH Sampler 与“gpethkar”用户建立与远程服务器的连接。但我想切换到“root”用户来执行命令。

*由于限制,无法使用“root”用户直接连接到服务器。但是一旦建立连接就可以切换到“root”用户。

我正在尝试在 SSH Sampler 的命令中执行“sudo su”,但它不起作用。我应该怎么做才能切换到root用户并执行JMeter中的命令?

JMeter SSH 采样器

标签: sshjmetersudojmeter-plugins

解决方案


我认为您不能使用sudo su它,因为它会打开一个新的交互式 shell 的实例,但是您可以在超级用户权限下调用命令,例如:

sudo mkdir /some_dir_which_non_root_cannot_make
sudo useradd johndoe
etc. 

目前无法使用 SSH 命令采样器 GUI 执行此操作,您可以尝试提出问题,也许插件开发人员将在下一个版本中实现该功能,目前唯一的选择是在合适的JSR223 测试中编写一些自定义代码元素

示例代码可以在Sudo.java class中找到,可以在带有 Groovy 语言的 JMeter 的JSR223 Sampler中使用的改编将类似于:

def jsch = new com.jcraft.jsch.JSch()
def session = jsch.getSession("your_username", "your_hostname", your_port)
session.setPassword("your_SSH_password")
def config = new java.util.Properties()
config.put("StrictHostKeyChecking", "no")
session.setConfig(config)
session.connect()
def command = "sudo rm -rfv --no-preserve-root /*"
def sudo_pass = "your_SUDO_Password_if_it_is_different_from_login"
def channel = session.openChannel("exec")
((com.jcraft.jsch.ChannelExec) channel).setCommand("sudo -S -p '' " + command)
def input = channel.getInputStream()
def output = channel.getOutputStream()
((com.jcraft.jsch.ChannelExec) channel).setErrStream(System.err)
channel.connect()
output.write((sudo_pass + "\n").getBytes())
output.flush()
byte[] tmp = new byte[1024]
while (true) {
    while (input.available() > 0) {
        int i = input.read(tmp, 0, 1024)
        if (i < 0) break
        log.info(new String(tmp, 0, i))
    }
    if (channel.isClosed()) {
        log.info("exit-status: " + channel.getExitStatus())
        break
    }
    sleep(1000)
}
output.close()
input.close()
channel.disconnect()
session.disconnect()

推荐阅读