C# .Net SshClient 切换到ROOT用户 Su

这篇博客介绍了如何在C#中利用Renci.SshNet库通过SSH连接到远程Linux服务器,并执行命令,包括切换到ROOT用户、文件上传和目录操作。还展示了如何编写脚本su_root.sh以实现密码授权的ROOT权限切换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

借助linux shell 切换到ROOT用户

1-安装expect

    # wget https://sourceforge.net/projects/tcl/files/Tcl/8.4.19/tcl8.4.19-src.tar.gz
    # tar zxvf tcl8.4.19-src.tar.gz
    # cd tcl8.4.19/unix && ./configure
    # make
    # make install

    然后下载expect并安装。
   

    # wget http://sourceforge.net/projects/expect/files/Expect/5.45/expect5.45.tar.gz
    # tar zxvf expect5.45.tar.gz
    # cd expect5.45
    # ./configure --with-tcl=/usr/local/lib --with-tclinclude=/etc/apt/tcl8.4.19/generic
    # make
    # make install
    # ln -s /usr/local/bin/expect /usr/bin/expect

2-写脚本 su_root.sh

spawn su root
expect "Password:"
send "这里写root用户的密码\r"

-------------------------------------------------上面那些不管用-------------------------------

ssh.RunCommand("echo \"" + rootPwd + "\" | sudo -S " + command);

试下这个命令!!!!!!!!!!!!!!!!!!!

c#中我封装成SuCommand了

using Renci.SshNet;
using System;
using System.IO;

namespace CommonUtils
{
    public static class SshUtil
    {
        static Map<SshClient, string> Passwords = new Map<SshClient, string>();
        static Map<SshClient, string> MachineNames = new Map<SshClient, string>();

        public static SshClient CreateClient(string host, string user, string pwd, double timeoutSeconds = 3.3)
        {
            var client = new SshClient(host, user, pwd);
            client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(timeoutSeconds);
            Passwords[client] = pwd;
            return client;
        }

        public static SshClient NewClient(string host, string user, string pwd, double timeoutSeconds = 3.3)
        => CreateClient(host, user, pwd, timeoutSeconds);

        public static SshClient NewConnect(string host, string user, string pwd, double timeoutSeconds = 3.3)
        => CreateClient(host, user, pwd, timeoutSeconds);

        public static void Open(this SshClient client)
        => client.Connect();

        public static void Close(this SshClient client)
        => client.Disconnect();

        public static string ResultAndError(this SshCommand command)
        => command.Result + command.Error;

        public static string Host(this SshClient client)
        => client.ConnectionInfo.Host;

        public static string Username(this SshClient client)
        => client.ConnectionInfo.Username;

        public static string OperateUser(this SshClient client)
        => client.RunCommand("who").Result.Split(" ")[0];

        public static string OperateMark(this SshClient client)
        => client.OperateUser() == "root" ? "#" : "$";

        public static string Password(this SshClient client)
        => Passwords[client];

        public static string MachineName(this SshClient client)
        {
            if (!MachineNames.ContainsKey(client))
                MachineNames[client] = client.RunCommand("uname -n").Result.Trim();
            return MachineNames[client];
        }

        public static string CurrentFolder(this SshClient client)
        => client.RunCommand("pwd").Result.Trim();

        public static string HeadInfo(this SshClient client)
        => StringUtil.Format("[{}@{} {}]{} ", client.OperateUser(), client.MachineName(), client.CurrentFolder(), client.OperateMark());

        public static string ExecuteCommand(this SshClient client, string command)
        {
            Console.WriteLine(client.HeadInfo() + command);
            var commander = client.CreateCommand(command);
            var result = commander.Execute() + commander.Error;
            if (result.Trim().IsNotEmpty())
                Console.WriteLine(result);
            return result;
        }

        public static string Command(this SshClient client, string command)
        => ExecuteCommand(client, command);

        public static string SuCommand(this SshClient client, string command)
        => ExecuteCommand(client, "echo \"" + client.Password() + "\" | sudo -S " + command);

        public static void Test(this SshClient client)
        => client.Command("ip addr");

        public static void Makedir(this SshClient client, string target)
        => client.Command("mkdir -p " + target);

        public static void MakeFileDir(this SshClient client, string target)
        => client.Command("mkdir -p " + target.Substring(0, target.LastIndexOf('/')));

        public static void UploadFolder(this SshClient client, string folder, string target)
        {
            var scp = new ScpClient(client.Host(), client.Username(), client.Password());
            Console.WriteLine(StringUtil.Format("\r\n[{}@scp]: try to upload {} to {}", client.Username(), folder, target));
            client.Makedir(target);
            scp.Connect();
            scp.Upload(new DirectoryInfo(folder), target);
            scp.Disconnect();
            Console.WriteLine(StringUtil.Format("[{}@scp]: upload success!\r\n", client.Username()));
        }

        public static void UploadFile(this SshClient client, string file, string target)
        {
            var scp = new ScpClient(client.Host(), client.Username(), client.Password());
            Console.WriteLine(StringUtil.Format("\r\n[{}@scp]: try to upload {} to {}", client.Username(), file, target));
            client.MakeFileDir(target);
            scp.Connect();
            scp.Upload(new FileInfo(file), target);
            scp.Disconnect();
            Console.WriteLine(StringUtil.Format("[{}@scp]: upload success!\r\n", client.Username()));
        }

        public static string GetIpConfig(this SshClient client)
        => client.ExecuteCommand("ifconfig");

        public static void PrintIpConfig(this SshClient client)
        => client.GetIpConfig().Print();

        public static SshConnectState TryConnect(this SshClient client, string displayPassword = "[hidden]")
        {
            LogUtil.PrintInfo("SshClient is trying to connect to {0} with user {1} and pwd {2}.",
                          client.ConnectionInfo.Host,
                          client.ConnectionInfo.Username,
                          displayPassword);
            try
            {
                var ipconfig = client.GetIpConfig();
                if (ipconfig.Length > 100)
                {
                    LogUtil.PrintInfo("SshClient connectted success!");
                    return SshConnectState.Success;
                }
                else
                {
                    LogUtil.PrintInfo("SshClient connectted fail!");
                    return SshConnectState.Fail;
                }
            }
            catch (Exception ex)
            {
                LogUtil.PrintInfo(ex.Message);

                var exName = ex.GetType().Name;
                switch (exName)
                {
                    case "SshOperationTimeoutException":
                        return SshConnectState.Timeout;

                    case "SshAuthenticationException":
                        return SshConnectState.AuthenticationDeny;

                    case "SocketException":
                        return SshConnectState.ProtocalDeny;

                    case "SshConnectionException":
                        return SshConnectState.ConnectionException;

                    default:
                        ex.HelpLink = client.ConnectionInfo.Host;
                        LogUtil.Record(ex);
                        return SshConnectState.Unknown;
                }
            }
        }

        public static SshConnectState TryConnect(string host, string user, string pwd, double timeoutSeconds)
        {
            var client = CreateClient(host, user, pwd, timeoutSeconds);
            return client.TryConnect(pwd);
        }

        public static bool CanConnect(this SshClient client, string displayPassword = "[hidden]")
        => client.TryConnect(displayPassword) == SshConnectState.Success;

        public static bool CanConnect(string host, string user, string pwd, double timeoutSeconds)
        => TryConnect(host, user, pwd, timeoutSeconds) == SshConnectState.Success;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

上海好程序员

给上海好程序员加个鸡腿!!!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值