【问题标题】:Running a script when connecting to server with ssh使用 ssh 连接到服务器时运行脚本
【发布时间】:2021-03-13 18:04:50
【问题描述】:

我使用的是 kitty 终端模拟器,所以当我连接到新服务器时,我(通常)需要添加 terminfo(至少,这种方式似乎可以工作)。为此,我编写了一个脚本。当我在做的时候,我添加了一些代码来添加一个公钥,如果用户想要的话。 与问题无关,但这里是代码:

#!/bin/bash
host=$1
ip=$(echo $host | cut -d@ -f2 | cut -d: -f1)
# Check if it is a unknown host
if [[ -z $(ssh-keygen -F $ip) ]]; then
    # Check if there are any ssh-keys
    if [ $(ls $HOME/.ssh/*.pub > /dev/null | wc -l) -ne 0 ]; then
        keys=$(echo $( (cd $HOME/.ssh/ && ls *.pub) | sed "s/.pub//g" ))
        ssh -q -o PubkeyAuthentication=yes -o PasswordAuthentication=no $host "ls > /dev/null 2>&1"
        # Check if the server has one of the public keys
        if [ $? -ne 0 ]; then
            echo "Do you want to add a SSh key to the server?"
            while true; do
                read -p " Choose [$keys] or leave empty to skip: " key
                if [[ -z $key ]]; then
                    break
                elif [[ -e $HOME/.ssh/$key ]]; then
                    # Give the server a public key
                    ssh $host "mkdir -p ~/.ssh && chmod 700 ~/.ssh && echo \"$(cat $HOME/.ssh/$key.pub)\" >> ~/.ssh/authorized_keys"
                    break
                else
                    echo "No key with the name \"$key\" found."
                fi
            done
        fi
    fi
    # Copy terminfo to server
    ssh -t $host "echo \"$(infocmp -x)\" > \"\$TERM.info\" && tic -x \"\$TERM.info\" && rm \$TERM.info"
fi

这不是最好的代码,但它似乎工作。当然欢迎提示。

问题是我每次连接新的远程服务器时都需要运行这个脚本(或者我需要跟踪哪个服务器是新的,但这更糟)。有没有办法在我每次连接到服务器时运行这个脚本(脚本检查 ip 是否是已知主机)。 还是有其他方法可以做到这一点?添加公钥很不错,但不是很重要。

希望有人能帮忙, 谢谢!

【问题讨论】:

    标签: ssh openssh


    【解决方案1】:

    有一个技巧可以识别您正在使用ssh 登录目标机器:

    pgrep -af "sshd.*"$USER |wc -l
    

    上面的命令会统计用户使用sshd的进程数

    您可以在目标机器中添加上述命令,以测试您是否通过ssh连接。将上述命令添加到目标机器中的.profile.bash_profile 脚本中。

    只有当您通过ssh 登录时,您的脚本才会在您登录/连接时在目标机器上运行启动脚本。

    目标机器上的样本.bash_profile

    #!/bin/bash
    # .bash_profile
    
    # Get the aliases and functions
    if [ -f ~/.bashrc ]; then
            . ~/.bashrc
    fi
    
    # User specific environment and startup programs
    if [[ $(pgrep -af "sshd.*"$USER |wc -l) -gt 0 ]];  then
        your_init_script
    fi
    

    【讨论】:

    • 这是错误的方法。每次我尝试连接到未知的目标机器时,我的本地机器都应该运行我的脚本。
    猜你喜欢
    • 2015-09-04
    • 1970-01-01
    • 2018-01-28
    • 2019-01-13
    • 2020-01-09
    • 1970-01-01
    • 1970-01-01
    • 2020-08-21
    • 1970-01-01
    相关资源
    最近更新 更多