Connect CISCO Anyconnect VPN via bash

前端 未结 5 1652
滥情空心
滥情空心 2020-12-25 08:52

As title says, trying to connect vpn via bash. The following script seemed closest to the answer I\'m looking for:

#!/bin/bash
/opt/cisco/anyconnect/bin/vpn          


        
5条回答
  •  暖寄归人
    2020-12-25 09:20

    c# solution ... in this case profile is the group name.

    //file = @"C:\Program Files (x86)\Cisco\Cisco AnyConnect Secure Mobility Client\vpncli.exe"
    var file = vpnInfo.ExecutablePath;
    var host = vpnInfo.Host;
    var profile = vpnInfo.ProfileName;
    var user = vpnInfo.User;
    var pass = vpnInfo.Password;
    var confirm = "y";
    
    var proc = new Process
    {
        StartInfo = new ProcessStartInfo
        {
            FileName = file,
            Arguments = string.Format("-s"),
            UseShellExecute = false,
            RedirectStandardInput = true,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
        }
    };
    
    proc.OutputDataReceived += (s, a) => stdOut.AppendLine(a.Data);
    proc.ErrorDataReceived += (s, a) => stdOut.AppendLine(a.Data);
    
    //make sure it is not running, otherwise connection will fail
    var procFilter = new HashSet() { "vpnui", "vpncli" };
    var existingProcs = Process.GetProcesses().Where(p => procFilter.Contains(p.ProcessName));
    if (existingProcs.Any())
    {
        foreach (var p in existingProcs)
        {
            p.Kill();
        }
    }
    
    proc.Start();
    proc.BeginOutputReadLine();
    
    //simulate profile file
    var simProfile = string.Format("{1}{0}{2}{0}{3}{0}{4}{0}{5}{0}"
        , Environment.NewLine
        , string.Format("connect {0}", host)
        , profile
        , user
        , pass
        , confirm
        );
    
    proc.StandardInput.Write(simProfile);
    proc.StandardInput.Flush();
    
    //todo: these should be configurable values
    var waitTime = 500; //in ms
    var maxWait = 10;
    
    var count = 0;
    var output = stdOut.ToString();
    while (!output.Contains("state: Connected"))
    {
        if (count > maxWait)
            throw new Exception("Unable to connect to VPN.");
    
        Thread.Sleep(waitTime);
        output = stdOut.ToString();
        count++;
    }
    stdOut.Append("VPN connection established! ...");
    

提交回复
热议问题