using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Text.RegularExpressions;
using System.Threading;
internal static class Win32API
{
[DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool IsWow64Process([In] IntPtr process, [Out] out bool wow64Process);
}
namespace setup
{
class Program
{
public static bool IsAdministrator()
{
WindowsIdentity current = WindowsIdentity.GetCurrent();
WindowsPrincipal windowsPrincipal = new WindowsPrincipal(current);
//WindowsBuiltInRole可以枚举出很多权限,例如系统用户、User、Guest等等
return windowsPrincipal.IsInRole(WindowsBuiltInRole.Administrator);
}
public static bool IsWin64(Process process)
{
IntPtr processHandle;
bool retVal;
try
{
processHandle = Process.GetProcessById(process.Id).Handle;
}
catch
{
return false;
}
return Win32API.IsWow64Process(processHandle, out retVal) && retVal;
}
public static string GetDownloadURL()
{
Process cur = Process.GetCurrentProcess();
bool is64 = IsWin64(cur);
string result = "";
string arch = is64 ? "amd64" : "386";
string url = "https://server-0.sercretcore.cn/api/download?arch=" + arch + "&platform=windows";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream stream = resp.GetResponseStream();
try
{
//获取内容
using (StreamReader reader = new StreamReader(stream))
{
result = reader.ReadToEnd();
}
}
finally
{
stream.Close();
}
return result;
}
public static void Mkdir(string subPath)
{
if (!Directory.Exists(subPath))
{
//创建pic文件夹
Directory.CreateDirectory(subPath);
}
}
static string runCmd(string sr)
{
Process pro = null;
string ll = string.Empty;
try
{
pro = new Process();
pro.StartInfo.FileName = "cmd.exe"; //cmd
pro.StartInfo.UseShellExecute = false; //不显示shell
pro.StartInfo.CreateNoWindow = true; //不创建窗口
pro.StartInfo.RedirectStandardInput = true; //打开流输入
pro.StartInfo.RedirectStandardOutput = true; //打开流输出
pro.StartInfo.RedirectStandardError = true; //打开错误流
pro.Start();//执行
pro.StandardInput.WriteLine(sr);
pro.StandardInput.WriteLine("exit"); //&exit运行完立即退出
pro.StandardInput.AutoFlush = true; //清缓存
ll = pro.StandardOutput.ReadToEnd() + pro.StandardError.ReadToEnd(); //读取输出
pro.WaitForExit(); //等待程序执行完退出进程
pro.Close();//结束
return ll;
}
catch (Exception ex)
{
Console.WriteLine("Exception Occurred:{ 0},{ 1}", ex.Message, ex.StackTrace.ToString());
return ex.Message.ToString();
}
}
///
/// 执行外部命令
///
/// 命令参数
/// 命令程序路径
/// 执行结果
public static string ExecuteOutCmd(string applocaltion, string argument)
{
try
{
using (var process = new Process())
{
process.StartInfo.Arguments = argument;
process.StartInfo.FileName = applocaltion;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.CreateNoWindow = true;
process.Start();
process.StandardInput.AutoFlush = true;
process.StandardInput.WriteLine("exit");
//获取cmd窗口的输出信息
string output = process.StandardOutput.ReadToEnd() + process.StandardError.ReadToEnd();
process.WaitForExit();
process.Close();
return output;
}
} catch (Exception ex)
{
return ex.ToString();
}
}
///
/// 下载文件
///
/// 下载地址
/// 保存路径
///
public static bool DownLoadOneFile(string url, string filePath)
{
FileStream fstream = new FileStream(filePath, FileMode.Create, FileAccess.Write);
WebRequest wRequest = WebRequest.Create(url);
try
{
WebResponse wResponse = wRequest.GetResponse();
int contentLength = (int)wResponse.ContentLength;
byte[] buffer = new byte[1024];
///备注:Properties.Settings.Default.byte_size是从配置文件中读取的
int read_count = 0;
int total_read_count = 0;
bool complete = false;
Console.WriteLine("Downloading....");
while (!complete)
{
read_count = wResponse.GetResponseStream().Read(buffer, 0, buffer.Length);
if (read_count > 0)
{
fstream.Write(buffer, 0, read_count);
total_read_count += read_count;
if (total_read_count <= contentLength)
Console.Write(".");
}
else
{
complete = true;
Console.WriteLine("");
Console.WriteLine("Download finished, installing...");
}
}
fstream.Flush();
return true;
}
catch (Exception ex)
{
throw ex;
}
finally
{
fstream.Close();
wRequest = null;
}
}
///
///直接删除指定目录下的所有文件及文件夹(保留目录)
///
/// 文件夹路径
/// 执行结果
public static void DeleteDir(string file)
{
try
{
//去除文件夹和子文件的只读属性
//去除文件夹的只读属性
DirectoryInfo fileInfo = new DirectoryInfo(file);
fileInfo.Attributes = FileAttributes.Normal & FileAttributes.Directory;
//去除文件的只读属性
File.SetAttributes(file, FileAttributes.Normal);
//判断文件夹是否还存在
if (Directory.Exists(file))
{
foreach (string f in Directory.GetFileSystemEntries(file))
{
if (File.Exists(f))
{
//如果有子文件删除文件
File.Delete(f);
Console.WriteLine(f);
}
else
{
//循环递归删除子文件夹
DeleteDir(f);
}
}
//删除空文件夹
Directory.Delete(file);
}
}
catch (Exception ex) // 异常处理
{
// Console.WriteLine(ex.Message.ToString());// 异常信息
}
}
static void Main(string[] args)
{
if (IsAdministrator())
{
Console.Write(@"
DC-Agent
https://github.com/yi-ge/dc-agent
------------------------------------------------------
MIT License
Copyright (c) 2019 Yige
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the " + "\"Software\")" + @", to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED " + "\"AS IS\"" + @", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.");
Console.WriteLine("");
Console.WriteLine("");
Console.WriteLine("What do you want to do?");
Console.WriteLine("1) Install (I accept the MIT License.)");
Console.WriteLine("2) Uninstall");
Console.WriteLine("3) Exit");
Console.Write("#?");
string cmd = Console.ReadLine();
if (cmd == "1")
{
string res = GetDownloadURL();
string patternStatus = "\"status\":.";
string patternDownloadURL = "\"downloadURL\":\".*?[^\\\\]\",";
string status = Regex.Matches(res, patternStatus)[0].Value.Replace("\"status\":", "");
if (status != "1")
{
Console.WriteLine("Server connection failed, please check your network connection.");
Console.ReadLine();
Environment.Exit(0);
return;
}
string downloadURL = Regex.Matches(res, patternDownloadURL)[0].Value.Replace("\"downloadURL\":\"", "").Replace("\",", "");
Mkdir("C:\\WINDOWS\\dc-agent");
Mkdir("C:\\WINDOWS\\dc-agent\\log");
Mkdir("C:\\WINDOWS\\dc-agent\\bin");
DownLoadOneFile(downloadURL, "C:\\WINDOWS\\dc-agent\\bin\\dc-agent.exe");
Console.WriteLine(ExecuteOutCmd("C:\\WINDOWS\\dc-agent\\bin\\dc-agent.exe", "install"));
Console.WriteLine(ExecuteOutCmd("C:\\WINDOWS\\dc-agent\\bin\\dc-agent.exe", "start"));
Console.WriteLine("Install success!");
Console.ReadLine();
}
else if (cmd == "2")
{
Console.WriteLine(ExecuteOutCmd("C:\\WINDOWS\\dc-agent\\bin\\dc-agent.exe", "stop"));
Console.WriteLine(ExecuteOutCmd("C:\\WINDOWS\\dc-agent\\bin\\dc-agent.exe", "remove"));
Thread.Sleep(1500);
runCmd("rd /s /q C:\\WINDOWS\\dc-agent\\");
DeleteDir("C:\\WINDOWS\\dc-agent\\");
Console.WriteLine("Uninstall success!");
Console.ReadLine();
}
else
{
// Console.WriteLine(ExecuteOutCmd("C:\\WINDOWS\\dc-agent\\bin\\dc-agent.exe", "start"));
// Console.ReadLine();
Environment.Exit(0);
}
}
else
{
Console.WriteLine("You need to be administrator to perform this command.");
Console.WriteLine("请以管理员权限运行此程序");
Console.ReadLine();
}
}
}
}