diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..1ff0c42 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,63 @@ +############################################################################### +# Set default behavior to automatically normalize line endings. +############################################################################### +* text=auto + +############################################################################### +# Set default behavior for command prompt diff. +# +# This is need for earlier builds of msysgit that does not have it on by +# default for csharp files. +# Note: This is only used by command line +############################################################################### +#*.cs diff=csharp + +############################################################################### +# Set the merge driver for project and solution files +# +# Merging from the command prompt will add diff markers to the files if there +# are conflicts (Merging from VS is not affected by the settings below, in VS +# the diff markers are never inserted). Diff markers may cause the following +# file extensions to fail to load in VS. An alternative would be to treat +# these files as binary and thus will always conflict and require user +# intervention with every merge. To do so, just uncomment the entries below +############################################################################### +#*.sln merge=binary +#*.csproj merge=binary +#*.vbproj merge=binary +#*.vcxproj merge=binary +#*.vcproj merge=binary +#*.dbproj merge=binary +#*.fsproj merge=binary +#*.lsproj merge=binary +#*.wixproj merge=binary +#*.modelproj merge=binary +#*.sqlproj merge=binary +#*.wwaproj merge=binary + +############################################################################### +# behavior for image files +# +# image files are treated as binary by default. +############################################################################### +#*.jpg binary +#*.png binary +#*.gif binary + +############################################################################### +# diff behavior for common document formats +# +# Convert binary document formats to text before diffing them. This feature +# is only available from the command line. Turn it on by uncommenting the +# entries below. +############################################################################### +#*.doc diff=astextplain +#*.DOC diff=astextplain +#*.docx diff=astextplain +#*.DOCX diff=astextplain +#*.dot diff=astextplain +#*.DOT diff=astextplain +#*.pdf diff=astextplain +#*.PDF diff=astextplain +#*.rtf diff=astextplain +#*.RTF diff=astextplain diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3c4efe2 --- /dev/null +++ b/.gitignore @@ -0,0 +1,261 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# DNX +project.lock.json +project.fragment.lock.json +artifacts/ + +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# TODO: Comment the next line if you want to checkin your web deploy settings +# but database connection strings (with potential passwords) will be unencrypted +#*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/packages/* +# except build/, which is used as an MSBuild target. +!**/packages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/packages/repositories.config +# NuGet v3's project.json files produces more ignoreable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +node_modules/ +orleans.codegen.cs + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +*.mdf +*.ldf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml + +# CodeRush +.cr/ + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc \ No newline at end of file diff --git a/setup.sh b/setup.sh index 625d626..55b0b7f 100755 --- a/setup.sh +++ b/setup.sh @@ -122,7 +122,13 @@ Uninstall() { echo -e "\nUninstall success!\n" } -echo "MIT License +echo " +DC-Agent + +https://github.com/yi-ge/dc-agent +------------------------------------------------------ + +MIT License Copyright (c) 2019 Yige diff --git a/setup.sln b/setup.sln new file mode 100644 index 0000000..2cb510e --- /dev/null +++ b/setup.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.28307.779 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "setup", "setup\setup.csproj", "{839F4F55-2904-4A2B-BDBD-D515958F816E}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {839F4F55-2904-4A2B-BDBD-D515958F816E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {839F4F55-2904-4A2B-BDBD-D515958F816E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {839F4F55-2904-4A2B-BDBD-D515958F816E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {839F4F55-2904-4A2B-BDBD-D515958F816E}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {DA864C2D-F4CC-46E5-9B4C-A9B3E3DC007B} + EndGlobalSection +EndGlobal diff --git a/setup/Program.cs b/setup/Program.cs new file mode 100644 index 0000000..c529ff1 --- /dev/null +++ b/setup/Program.cs @@ -0,0 +1,353 @@ +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")); + + // DeleteDir("C:\\WINDOWS\\dc-agent\\"); + Thread.Sleep(1500); + + runCmd("rd /s /q 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(); + } + } + } +} diff --git a/setup/Properties/AssemblyInfo.cs b/setup/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..30695a1 --- /dev/null +++ b/setup/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("setup")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("setup")] +[assembly: AssemblyCopyright("Copyright © 2019")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 会使此程序集中的类型 +//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("839f4f55-2904-4a2b-bdbd-d515958f816e")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +// 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号 +// 方法是按如下所示使用“*”: : +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/setup/Properties/app.manifest b/setup/Properties/app.manifest new file mode 100644 index 0000000..15b2b8c --- /dev/null +++ b/setup/Properties/app.manifest @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/setup/setup.csproj b/setup/setup.csproj new file mode 100644 index 0000000..c054899 --- /dev/null +++ b/setup/setup.csproj @@ -0,0 +1,80 @@ + + + + + Debug + AnyCPU + {839F4F55-2904-4A2B-BDBD-D515958F816E} + Exe + setup + setup + v2.0 + 512 + true + false + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 0 + 1.0.0.%2a + false + true + + + x86 + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + true + + + AnyCPU + none + true + bin\Release\ + TRACE + prompt + 4 + false + + + LocalIntranet + + + false + + + Properties\app.manifest + + + + + + + + + + + + + + + + False + .NET Framework 3.5 SP1 + true + + + + \ No newline at end of file