在Jenkins Freestyle Job中添加Shell脚本并执行SSH命令

103次阅读
没有评论

问题描述

在Jenkins中使用Freestyle Job时,需要在Execute Shell步骤中运行一个Shell脚本,并且希望在环境中执行SSH命令,同时要求使用无密码认证进行连接。

解决方案

请注意以下操作注意版本差异及修改前做好备份。

步骤1:在Jenkins Freestyle Job中执行Shell脚本

  1. 打开Jenkins管理界面,导航到你的Freestyle Job配置页面。
  2. 在”构建”部分,点击”增加构建步骤”,选择”Execute shell”。
  3. 在”Execute shell”文本框中,输入以下脚本,该脚本为你提供的Shell脚本,并指定所需的Shell和选项:
    bash
    #!/bin/bash
    du -sh /bbhome/shared/data/repositories/* | sort -h | tail -20 | while IFS= read -r line; do
    DIR=`echo $line | awk '{print $2}'`
    Rep=`cat $DIR/repository-config | grep 'project\|repo' | tr '\n' ' '`
    Size=`echo $line | awk '{print $1}' `
    echo $Size $Rep
    done

    注意:上述脚本将输出结果打印到控制台。

步骤2:通过SSH执行命令

如果你希望在远程机器上执行SSH命令,可以按照以下步骤进行设置:

  1. 在”构建”部分,点击”增加构建步骤”,选择”Execute shell”。
  2. 在”Execute shell”文本框中,输入以下脚本,将SSH命令添加到环境中并执行相关逻辑:
    bash
    #!/bin/bash
    ssh -o StrictHostKeyChecking=no user@host '
    command_1 to execute
    command_2 to execute
    ./script.sh to execute
    command_3 to execute
    '

    user@host替换为你的SSH目标主机的用户名和主机名,然后按需添加要执行的命令,包括运行你的脚本(例如./script.sh)。

注意事项

  • 为了使用无密码认证进行SSH连接,确保你的Jenkins服务器和目标主机之间已经设置了SSH密钥认证。你需要将Jenkins服务器的公钥添加到目标主机的~/.ssh/authorized_keys文件中。
  • 在设置SSH连接时,确保SSH目标主机的主机密钥验证被禁用,以避免交互式确认。这可以通过-o StrictHostKeyChecking=no选项来实现。

示例

以下是一个完整的示例,展示了如何在Jenkins Freestyle Job中执行Shell脚本并通过SSH在远程机器上执行命令:

#!/bin/bash
# Step 1: Execute Shell script
du -sh /bbhome/shared/data/repositories/* | sort -h | tail -20 | while IFS= read -r line; do
    DIR=`echo $line | awk '{print $2}'`
    Rep=`cat $DIR/repository-config | grep 'project\|repo' | tr '\n' ' '`
    Size=`echo $line | awk '{print $1}' `
    echo $Size $Rep
done

# Step 2: Execute SSH command
ssh -o StrictHostKeyChecking=no user@host '
    command_1 to execute
    command_2 to execute
    ./script.sh to execute
    command_3 to execute
'

请根据你的实际需求进行适当的替换和调整。

以上方案适用于Jenkins Freestyle Job中执行Shell脚本并通过SSH执行命令的情况。如果你使用的是Jenkins Pipeline Job,操作步骤可能会略有不同。

希望以上解决方案对你有帮助!如果你还有其他问题或需要进一步的帮助,请随时提问。

正文完